js array traversal method summary
Array traversal method
1.for loop
Use temporary variables to cache the length to avoid repeatedly obtaining the array length. The optimization effect will be more obvious when the array is large.
1 2 3 for(j = 0,len=arr.length; j < len; j++) { }
2.foreach cycle
Traverse each item in the array, no return value, no impact on the original array, and IE is not supported
1 2 3 4 5 6 //1 has no return value arr.forEach((item,index,array)=>{ //Execute code }) //Parameters: current item in value array, index of current item, array original array; //If there are several items in the array, the anonymous callback function passed in needs to be executed several times;
3.map loop
If you have a return value, you can return it
The return value of return is supported in the callback function of map; Return is equivalent to changing this item in the array (it does not affect the original array, but it is equivalent to cloning one copy of the original array and changing the corresponding item in the cloned array);
1 2 3 4 5 6 7 arr.map(function(value,index,array){ //do something return XXX })
1 2 3 4 5 6 var ary = [12,23,24,42,1]; var res = ary.map(function (item,index,ary ) { return item*10; }) console.log(res);//-->[120,230,240,420,10]; The original array is copied and modified console.log(ary);//-->[12,23,24,42,1]; The original array has not changed
4.forof traversal
You can correctly respond to break, continue, and return statements
1 2 3 for (var value of myArray) { console.log(value); }
5.filter traversal
The original array will not be changed, and a new array will be returned
1 2 3 4 5 var arr = [ { id: 1, text: 'aa', done: true }, { id: 2, text: 'bb', done: false } ] console.log(arr.filter(item => item.done))
To ES5
1 2 3 arr.filter(function (item) { return item.done; });
1 2 3 var arr = [73,84,56, 22,100] var newArr = arr.filter(item => item>80) //Get new array [84, 100] console.log(newArr,arr)
6.every traversal
every() runs the given function for each item in the array. If the function returns true for each item, it returns true.
1 2 3 4 5 var arr = [ 1, 2, 3, 4, 5, 6 ]; console.log( arr.every( function( item, index, array ){ return item > 3; })); false
7.some traversal
some() runs the specified function for each item in the array. If the function returns true for any item, it returns true.
1 2 3 4 5 6 var arr = [ 1, 2, 3, 4, 5, 6 ]; console.log( arr.some( function( item, index, array ){ return item > 3; })); true
8.reduce
reduce() Method receives a function as an accumulator, and each value in the array (from left to right) is reduced to a value.
1 var total = [0,1,2,3,4].reduce((a, b)=>a + b); //10
reduce accepts a function with four parameters: the previous value, the current value, the index of the current value, and the array
1 2 3 [0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue; });
reduce also has a second parameter. We can use this parameter as the first parameter when calling callback for the first time. In the above example, because there is no second parameter, we start directly from the second item of the array. If we give the second parameter as 5, the result is as follows:
1 2 3 [0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue; },5);
The value of the previousValue of the first call is replaced by the second parameter passed in,
9.reduceRight
The function of reduceRight() method is the same as that of reduce(). The difference is that reduceRight() accumulates the array items in the array from the end of the array to the front.
When reducereight() calls the callback function callbackfn for the first time, prevvalue and curValue Can be one of two values. If called reduceRight() Provided at initialValue Parameter, then prevValue be equal to initialValue,curValue Equal to the last value in the array. If not provided initialValue Parameter, then prevValue Equal to the last value of the array, curValue Equal to the penultimate value in the array.
1 2 3 4 5 var arr = [0,1,2,3,4]; arr.reduceRight(function (preValue,curValue,index,array) { return preValue + curValue; }); // 10
The callback will be called four times. The parameters and return values of each call are as follows:
If an initial value is provided, the initialValue is 5:
1 2 3 4 5 var arr = [0,1,2,3,4]; arr.reduceRight(function (preValue,curValue,index,array) { return preValue + curValue; }, 5); // 15
The callback will be called five times. The parameters and returned values of each call are as follows:
Similarly, you can sum an array or use the reduceRight() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 var arr = [1,2,3,4,5,6]; console.time("ruduceRight"); Array.prototype.ruduceRightSum = function (){ for (var i = 0; i < 10000; i++) { return this.reduceRight (function (preValue, curValue) { return preValue + curValue; }); } } arr.ruduceRightSum(); console.log('Final value:' + arr.ruduceSum()); // 21 console.timeEnd("ruduceRight"); // 5.725ms
10.find
The find() method returns the first element in the array that meets the conditions of the test function. Otherwise, undefined is returned
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 var stu = [ { name: 'Zhang San', gender: 'male', age: 20 }, { name: 'Xiao Mao Wang', gender: 'male', age: 20 }, { name: 'Li Si', gender: 'male', age: 20 } ]
1 2 3 4 5 6 7 function getStu(element){ return element.name == 'Li Si' } stu.find(getStu) //The returned result is //{name: "Li Si", gender: "male", age: 20}
ES6 method
1 stu.find((element) => (element.name == 'Li Si'))
11.findIndex
For each element in the array, FindIndex Methods will call the callback function once (in ascending index order) until an element returns true. As long as one element returns true, FindIndex Returns the index value of the element that returns true immediately. If none of the elements in the array returns true, then findIndex Returns - 1.
findIndex Array objects are not changed.
1 2 [1,2,3].findIndex(function(x) { x == 2; }); // Returns an index value of 1.
1 2 [1,2,3].findIndex(x => x == 4); // Returns an index value of -1.
12.keys,values,entries
ES6 provides three new methods -- entries (), keys (), and values () -- for traversing arrays. They all return an ergodic object, which can be traversed by the for...of loop. The only difference is that keys() is the traversal of key names, values() is the traversal of key values, and entries() is the traversal of key value pairs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 for (let index of ['a', 'b'].keys()) { console.log(index); } // 0 // 1 for (let elem of ['a', 'b'].values()) { console.log(elem); } // 'a' // 'b' for (let [index, elem] of ['a', 'b'].entries()) { console.log(index, elem); } // 0 "a" // 1 "b"