es6 遍歷總結
阿新 • • 發佈:2019-02-13
efi pan spa res str 支持 var class urn
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 inarray){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]
未完待續。。。
es6 遍歷總結