for loop, foreach, map, reduce the use of contrast + for in, for of

for not to repeat them, it is quite simple;

foreach method :

forEach () method calls for each element of the array, and passed to the callback function element.

Note:  forEach () for an empty array will not be implemented callback function.

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

map() :

map () method returns a new array, the array element calls a function of the value of the original processing array elements.

map () method in the original order of the processing elements in the array elements.

Note:  the Map () will not be an empty array detection.

Note:  the Map () does not alter the original array.

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

Seen from the above: foreach, map the parameter is identical

reduce() :

reduce () method takes a function as an accumulator, each value in the array (left to right) started to shrink, and finally calculated as a return value.

reduce () function as a higher order, for compose function.

Note:  the reduce () for an empty array will not be implemented callback function.

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

for in;for of:

for in

Use for in the party iterate

    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不能对象用

 

Guess you like

Origin www.cnblogs.com/wangtong111/p/11223351.html