for循环,foreach, map,reduce用法对比+for in,for of

for不做赘述,相当简单;

foreach方法

forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。

注意: forEach() 对于空数组是不会执行回调函数的。

array.forEach(function(currentValue, index, arr), thisValue)

map() :

map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

map() 方法按照原始数组元素顺序依次处理元素。

注意: map() 不会对空数组进行检测。

注意: map() 不会改变原始数组。

array.map(function(currentValue,index,arr), thisValue)

由以上可见:foreach, map参数是完全相同的

reduce() :

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值并返回。

reduce() 可以作为一个高阶函数,用于函数的 compose。

注意: reduce() 对于空数组是不会执行回调函数的。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

for in;for of:

for in

用for in的方遍历数组

    for(let index in array) {  
        console.log(index,array[index]);  
    };

用for in不仅可以对数组,也可以对enumerable对象操作

var A = {a:1,b:2,c:3,d:"hello world"};  
for(let k in A) {  
    console.log(k,A[k]);  
} 

for of

在ES6中,增加了一个for of循环,使用起来很简单

for(let v of array) {  
    console.log(v);  
}; 
 
let s = "helloabc"; 
for(let c of s) {  
    console.log(c); 
}

总结来说:for in总是得到对像的key或数组,字符串的下标,而for of和forEach一样,是直接得到值
for of不能对象用

原文地址:https://www.cnblogs.com/wangtong111/p/11223351.html