Js数组遍历方法对比总结
引言:
ES6为javascript为数组遍历提供了新的一种方式: for....of....。那之前的遍历方法各存在哪些缺点?for...of...有什么好处?接下来,我们先回顾一下有多少种方式。
方法:
第一种: for 循环

特点:
1. 代码不够简洁
2.常用,性能比较好,数组较大时,也需要优化。
第二种: forEach

特点:
代码比较简洁,但是没法中断停止整个循环,性能比for弱
第三种: for ....in...

特点:
更常用于对象遍历,注意点输出的i 是一个字符串类型,非数值类型,要用,通常还得转换,效率也比较低
第四种:for...of... (es6新增)

特点:
1. 可以用break终止循环,continute跳出当前循环,继续后面的循环
2. 用keys()方法获得数值型索引。
4. 能遍历的对象有:数组,类数组对象,字符串,set和map结构等具有iterator接口的数据结构
第五种: filter

特点:
不会对空数组检测 ,不会改变原始数组
第六种:map

特点:支持return 返回值,实际使用效率比foreach还低
第七种:every

特点:
检测数组所有元素都符合条件返回true,否则返回false.
第八种: some

特点:
检测数组只要有一个符合条件就返回true,剩下元素不会再继续执行,全部不符合返回false
第9种:reduce & reduceRight

特点:
reduce ()接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值
reduceRigh() 跟reduce不一样的是 他是从右边到左边。
第10种: find() & findIndex()

特点:
1.find() 返回数组中符合测试函数条件的第一个元素。否则返回undefined 。
2.findIndex() 返回数组中符合测试函数条件的第一个元素位置