js loop array (summary)
A summary
Sentence summary:
for循环:for(j = 0,len=arr.length; j < len; j++) {}
foreach loop: arr.forEach ((item, index, array) => {// execute code})
forof遍历:for (var value of myArray) { }
1, a simple optimization for loop: for (j = 0, len = arr.length; j <len; j ++) {}?
Using a temporary variable, the length cached, to avoid duplication of acquiring the array length, when the array is large optimization effect will be more obvious.
2, foreach loop Note: arr.forEach ((item, index, array) => {// execute code})?
Through each item in the array, no return value, no effect on the original array, does not support IE
Parameters: the current item value array, index index of the current item, array original array;
Several array, then passing in an anonymous callback function will need to be performed several times;
Two, js array traversal Methods
Transfer or Reference: js array traversal Methods
https://www.cnblogs.com/woshidouzia/p/9304603.html
Array traversal methods
1.for circulation
Using a temporary variable, the length cached, to avoid duplication of acquiring the array length, when the array is large optimization effect will be more obvious.
for(j = 0,len=arr.length; j < len; j++) { }
2.foreach cycle
Through each item in the array, no return value, no effect on the original array, does not support IE
1 // No Return Value arr.forEach ((Item, index, array) => { // execute code }) // parameters: the current item value array, index index of the current item, array original array; // Array there are a few, then passing in an anonymous callback function will need to be performed several times;
3.map cycle
Returns a value, you can return it
map of the callback function return value to support return; return is valid, equivalent to an array of why this one change (does not affect the original array, the original array is equivalent to just a clone, the clone of this parts corresponding to the changed item in the array);
arr.map(function(value,index,array){ //do something return XXX })
ary = var [12,23,24,42,1]; var ary.map RES = (function (Item, index, ary) { return Item 10 *; }) the console.log (RES); // -> [120,230,240,420,10]; a copy of the original array, and revised console.log (ary); // -> [12,23,24,42,1]; the original array has not changed
4.forof traversal
You can respond properly break, continue, and return statement
for (var value of myArray) { console.log(value); }
5.filter traversal
It does not alter the original array and returns a new array
var arr = [ { id: 1, text: 'aa', done: true }, { id: 2, text: 'bb', done: false } ] console.log(arr.filter(item => item.done))
Into ES5
arr.filter(function (item) { return item.done; });
ARR = var [73,84,56, 22,100] var = newArr arr.filter (Item => Item> 80) // get a new array [84, 100] the console.log (newArr, ARR)
6.every traversal
every () is run on each item in the array to a given function, the function returns true if for each, it returns true.
var arr = [ 1, 2, 3, 4, 5, 6 ]; console.log( arr.every( function( item, index, array ){ return item > 3; })); false
7.some traversal
some () function is specified for each item in the array operation, a Returns true if any of the function, it returns true.
var arr = [ 1, 2, 3, 4, 5, 6 ]; console.log( arr.some( function( item, index, array ){ return item > 3; })); true
8.reduce
reduce()
The method of receiving a function as an accumulator (ACC with), each value (left to right) in the array begins to reduce, to a final value.
var total = [0,1,2,3,4].reduce((a, b)=>a + b); //10
reduce
Receiving a function, the function has four parameters, namely: the previous value, the current value of the index, the current values of array
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue; });
reduce
There is a second argument, we can put this parameter as the first call to callback
the first parameter of the above example because there is no second argument, so start directly from the second item in the array, if we give the second argument is 5, then the result is this:
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue; },5);
The first call of the previousValue
value to be replaced by the incoming second argument,
9.reduceRight
reduceRight()
Function and method of reduce()
function is the same, except that reduceRight()
the forward end of the array of items in the array to array do accumulate.
reduceRight()
The first call to the callback function callbackfn
when, prevValue
and curValue
can be one of two values. If the call reduceRight()
is provided when the initialValue
parameter is prevValue
equal initialValue
, curValue
equal to the last value in the array. If no initialValue
parameter is prevValue
equal to the last value of the array, curValue
it is equal to the reciprocal of the second value in the array.
var arr = [0,1,2,3,4]; arr.reduceRight(function (preValue,curValue,index,array) { return preValue + curValue; }); // 10
Callback will be called four times, each call parameters and return values are as follows:
If an initial value provided initialValue
to 5
:
var arr = [0,1,2,3,4]; arr.reduceRight(function (preValue,curValue,index,array) { return preValue + curValue; }, 5); // 15
Callback will be called five times, each call parameters and return values are as follows:
Similarly, an array of summing may also be used reduceRight()
methods:
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('最终的值:' + arr.ruduceSum()); // 21 console.timeEnd("ruduceRight"); // 5.725ms
10.find
find()方法返回数组中符合测试函数条件的第一个元素。否则返回undefined
var stu = [ { name: '张三', gender: '男', age: 20 }, { name: '王小毛', gender: '男', age: 20 }, { name: '李四', gender: '男', age: 20 } ]
function getStu(element){ return element.name == '李四' } stu.find(getStu) //返回结果为 //{name: "李四", gender: "男", age: 20}
ES6方法
stu.find((element) => (element.name == '李四'))
11.findIndex
对于数组中的每个元素,findIndex 方法都会调用一次回调函数(采用升序索引顺序),直到有元素返回 true。只要有一个元素返回 true,findIndex 立即返回该返回 true 的元素的索引值。如果数组中没有任何元素返回 true,则 findIndex 返回 -1。
findIndex 不会改变数组对象。
[1,2,3].findIndex(function(x) { x == 2; }); // Returns an index value of 1.
[1,2,3].findIndex(x => x == 4); // Returns an index value of -1.
12.keys,values,entries
ES6 提供三个新的方法 —— entries(),keys()和values() —— 用于遍历数组。它们都返回一个遍历器对象,可以用for...of循环进行遍历,唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历
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"