方法一 使用 .entries()
let arr = ['a','b','c'] for (let [index,item] of arr.entries()){ console.log(index,item) } //0 "a" //1 "b" //2 "c"
方法二 借助 Map
数组的 for... of 遍历本身获取不了 index,可以先将 Array 转成 Map,再用 for... of 遍历
let arr = [ 'a', 'b', 'c' ]; for( let [ index, item ] of new Map( arr.map( ( item, index ) => [ index, item ] ) ) ) { console.log( index, item ); }
得到
0 "a"
1 "b"
2 "c"