遍历数组方法总结
1.普通for
for(j = 0; j < arr.length; j++) { }
简要说明: for最简单的一种,也是使用频率最高的一种,虽然性能不弱,但仍有优化空间
2. 优化版for
for(j = 0,len=arr.length; j < len; j++) { }
简要说明: 使用临时变量,将长度缓存起来,避免重复获取数组长度,当数组较大时优化效果才会比较明显。
这种方法基本上是所有循环遍历方法中性能最高的一种
3. foreach
arr.forEach(function(e){ });
简要说明: 数组自带的foreach循环,使用频率较高,实际上性能比普通for循环弱
没有返回值, 不允许在循环体内写return, 不会改变原来数组的内容.forEach()也可以循环对象
4. for...in
for(j in arr) { }
简要说明: 这个循环很多人爱用,但实际上,经分析测试,在众多的循环遍历方式中,
能正确响应break、continue和return语句
它的效率是最低的
5. map
arr.map(function(n){ });
简要说明: 但实际效率还比不上foreach,原数组被“映射”成对应新数组
1、forEach:用来遍历数组中的每一项,这个方法执行没有返回值,不影响原数组
2、map:支持return,相当与原数组克隆了一份,把克隆的每项改变了,也不影响原数组
6. for...of
for(let value of arr) { });
简要说明: 这种方式是es6里面用到的,性能要好于forin,但仍然比不上普通for循环
7. 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"
简要说明: 它们都返回一个遍历器对象,可以用for...of循环进行遍历,唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历
8. filter
var arr = [ { id: 1, text: 'aa', done: true }, {id:2,text: 'bb',done: false }]
arr.filter(item => item.done)
简要说明: filter会改变原始数组,返回新数组
9. every
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.every( function( item, index, array ){ return item > 3; })); false
简要说明: every是对数组中的每一项运行给定函数,如果该函数对每一项返回true,则返回true。
10.some
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.some( function( item, index, array ){return item > 3; })); true
简要说明: some是对数组中每一项运行指定函数,如果该函数对任一项返回true,则返回true
11.reduce
var total = [0,1,2,3,4].reduce((a, b)=>a + b); //10
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue;});
简要说明: reduce第一个参数是一个函数,函数有四个参数,分别是:上一次的值,当前值,当前值的索引,数组。 reduce第二个参数是第一次调用时的初始值,reduceRight:从数组的末尾向前将数组中的数组项做累加。
12. find
stu.find((element) => (element.name == '李四'))
简要说明: find方法返回数组中符合测试函数条件的第一个元素。否则返回undefined
13. findIndex
[1,2,3].findIndex(function(x) { x == 2; });// Returns an index value of 1.
简要说明: 只要有一个元素返回 true,findIndex 立即返回该返回 true 的元素的索引值。如果数组中没有任何元素返回 true,则findIndex返回 -1