es6 遍历总结

1、for in / for of

var array = [1,2,3,4,5];
for(let index in array)
{
    console.log(index, array[index]);
};
var obj = {a:1, b:2, c:"qqq"};
for(let index in obj)
{
    console.log(index, obj[index]);
};
for(let index of array){ 
    console.log(index)
}

注:for of 不支持对象,是直接得到值

for(let index in array){console.log(index, array[index]);};
0 1
1 2
2 3
3 4
4 5

for(let index of array){console.log(index, array[index]);}; 1 2
2 3
3 4
4 5
5 undefined

2、forEach

var array = [1,2,3,4,5];
var num = null;
var result = array.forEach( a => 
{
    num += a; return a+1; 
});
> console.log(result);
undefined
> console.log(num)
1 15
> console.log(array)
(5) [1, 2, 3, 4, 5]

未完待续。。。

猜你喜欢

转载自www.cnblogs.com/fogmisty/p/10371141.html