The method of the JS array element to add, delete, change, and other methods

Foreword

Yesterday the FBI a page, look on the page, but many interfaces.

Hot issues FBI configuration testing is completed (a total of 11 Synchronous Asynchronous Interface) 
1. New Configuration 
2. Configuration Editor 
Configuration delete 
4. Add hot spots 
5. The hot issue edit 
6. Remove the hot issues 
7. Move hot spots 
8. down hot spots 
9. stored hot spots 
10. The hot issue check 
list 11. hot issues

FIG case this one is the most troublesome, assembly of the other parts of the call, in order to reuse, the FBI for a long time.

Before packaging each component transfer operation is asynchronous interface behavior, this time into synchronous, submitted with the last saved.

So when the synchronization process, use a lot of additions and deletions to the array, the index value of the index change.

 

First, I would summarize all methods of array processing, then the method used here will be posted.


 

 A. Add elements

1.push (): push may receive any number of parameters, to add them to the array by one end , and the length of the array can be modified to return.

var sports = ['soccer', 'baseball']; var total = sports.push('football', 'swimming'); console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] console.log(total); // 4

2.unshift (): similar to Push (), may also receive any number of parameters, but the parameter is added to the array of individually foremost it also returns the new length of the array.

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

3.concat (): This method push () method somewhat similar, is also adding elements to the end of the array , but the array is not the original that array, but rather its copy , so after () will operate the array concat returns a new array .

        characteristic:

    1. It does not pass parameter and returns a copy of the current array
    2. An array of non-transmission parameters that will be added directly to the end of the array of results
    3. Array parameters passed, each element of the array, adding new array
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]

4. splice (): function is very powerful, focused plan

Three previous methods have significant limitations, because it is not added to the front array is an array , and splice () It is very flexible, it can add elements to anywhere in the array .

In addition it also has the added elements can remove and replace elements function.

splice () may be added to an array of any number of elements specified position.

We need to pass at least three parameters: splice (a, b, c, d, ......)

    • 1, a starting position of the element
    • 2, b the number of elements to be deleted, from the starting element starts count
    • 3, c is to be inserted behind the element can be an array

In summary, the principle is, in specified starting position a, b delete one, if the latter would need to go into a new element added to the cd ... the position, if not just delete, splice essentially by removing elements to achieve the insert, delete, replace

 

4.1 splice delete

Writing

array.splice(index,n);

Parameter Meaning

index: the starting position of the array need to delete data;

n: number of elements to be deleted, the data;

4.2 splice insert

Writing

array.splice(index,0,data1,data2,....);

parameter

index: the starting position of the array of data need to be inserted;

0: The number of deleted 0;

data1, data2: need to insert element, separated by commas

4.3 splice replacement

Writing

array.splice(index,n,data1,data2,......);

parameter

index: the starting position of the element needs to be replaced;

n: number of elements need to be replaced, in essence, is to remove;

data1, data2: need to insert element, separated by a comma;

 

Second, remove elements

1.pop (): with the push () method can constitute a LIFO stack, the method can delete the last item from the end of the array and returns the

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]

  2.shift (): the push () method with the use of FIFO queues may be formed, the method may remove and return the first item in the array .

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

  3.slice (): This method with concat () returns a new array is the same, does not affect the original array, but the slice () is used to cut an array and returns an array of cutting down.

slice () method can accept one or two parameters ,

1, a parameter, the parameter is returned from all the specified start position to the end of the current array .

2, two parameters, returned item between the start and end positions , including but not item end position.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

   4, splice (): which may be added in addition to the elements removed and replaced with further functional elements. Detailed look at the above example

 

Third, find elements

indexOf() 和 lastIndexOf()

Both methods accepts two parameters:

1, to find items

2, represents the starting point for the index to find the location. (Optional)

indexOf () to start looking backwards from the beginning of the array (position 0).

lastIndexOf () Finding forward from the beginning of the end of the array.

Two methods, when the element is not found, returns -1 

var arr = [1,2,3,4,5,2];
 
var index = arr.indexOf(2);
 
console.log(index);  // 1
 
index = arr.indexOf(2, 0);
console.log(index);  // 1
 
index = arr.indexOf(2, 2);
console.log(index);  // 5
 
index = arr.indexOf(6);
console.log(index);  // -1

 

Other methods:

This method is used to: 1.join () array to a string string, without changing the original array, returns the converted

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

2.sort (): ascii code by sort , changing the original array, returns a sorted array

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

3.reverse (): for reversing the array sequence elements. It returns an array after reversed changes the original array.

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

/* Careful: reverse is destructive. It also changes
the original array */
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

4.filter (): returns an array of new array of elements to meet the conditions of the original array unchanged (screening, filtration)

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

5.map (): map () method formatted according to the needs of the original array, return the array formatted . Original array unchanged. You can pass three values, namely ( the current element, the index index, map of the original array )

var arr = [1,2,3,4,5,2]; 
var arr2 = arr.map(function(current, index, array){
    console.log("当前元素current="+current + "索引index="+index +"数组array="+array)
    return "$"+current
})
console.log(arr) //[1, 2, 3, 4, 5, 2]
console.log(arr2) //["$1", "$2", "$3", "$4", "$5", "$2"]

6.every (): For each item in the array of runs given function, if each and every one return ture, then return true ($$)

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

7.some (): Each entry in the array is running a given function, if there is one or more return ture, otherwise it returns false (||)

const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

8.forEach (): traverse the entire array, without interruption, can pass three values, namely (the current element, the index index, the original array)

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

forEach and the map is very similar to a lot of places with one of the two will do

Same point:

  1. They are only iterate
  2. It has three return value (current element, the index index, the original array)
  3. Are each loop through the array

The difference is:

map, there is a return value, you can return it

forEach, no return value. forEach () return value is undefined, not chained calls.

      There is no way out of the termination or forEach () loop, unless an exception is thrown, so I want to perform an array of what conditions are met, returns a Boolean value, you can use a for loop to achieve a general, or with Array.every () or Array.some () ;

 

More questions about the difference between pen

[ "1", "2", ". 3"] Map (the parseInt);.   // Results [1, NaN, NaN] 

If you want a [1, 2,3] should do
function returnInt(element){
  return parseInt(element,10);
}
 
["1", "2", "3"].map(returnInt); 

This is mainly because parseInt () default has two parameters, the second parameter is a hexadecimal number. When parsrInt no incoming parameters, time and map the callback function () in, it will pass three parameters, the second parameter is the index, obviously incorrect, so the return NaN.


 

I write to you, find this article a long ah, I have written an hour. I do not know why the blog Park is not only one style of code introduced two get confused, you will see.

Posted the following about the project to achieve the top of the store function codes (technology stack react + mobx)

// Add a hot issue empty 
    @Action addHotItem = (obj) => { 
        const} {handledHotTopicContext = the this .currentItem; 
        const {List} = handledHotTopicContext
         the this .currentItem = { 
            ... the this .currentItem, 
            handledHotTopicContext: {. ..handledHotTopicContext, List: [List ..., obj], the selectedItem: null } 
        }; 
    } 

    // save a hotspot (new or modified) 
    @Action saveHotItem = (param, index) => { 
        const {ID} =  param;
        const} {handledHotTopicContext= this.currentItem;
        const { list } = handledHotTopicContext
        // 编辑
        if (id !== undefined) {
            list.splice(id, 1, param);
            this.currentItem = {
                ...this.currentItem,
                handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null }
            };
      // 新增 }
else { const leg = list.length - 1 const { name } = param const addObj = { id: leg, name: name } list.splice(leg, 1, addObj); // list.push(addObj) this.currentItem = { ...this.currentItem, handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null } }; } } // 删除一个热点问题 @action delHotItem = (param) => { const { id } = param; const { handledHotTopicContext } = this.currentItem; const { list } = handledHotTopicContext list.splice(id, 1); this.currentItem = { ...this.currentItem, handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null } }; } // 上移下移一个热点问题 @action moveHotItem = (item, key) => { let temp = null; const { id } = item; let index = 0; const { handledHotTopicContext } = this.currentItem; const { list } = handledHotTopicContext index = list.findIndex(ele => ele.id === item.id); if (key === 'up') { temp = { ...list[index - 1] }; list[index - 1] = { ...list[index] }; list[index] = temp; this.currentItem = { ...this.currentItem, handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null } }; } else { temp = { ...list[index + 1] }; list[index + 1] = { ...list[index] }; list[index] = temp; this.currentItem = { ...this.currentItem, handledHotTopicContext: { ...handledHotTopicContext, list: [...list], selectedItem: null } }; } }

 

 

  

Guess you like

Origin www.cnblogs.com/rong88/p/11947252.html