js中for of遍历数组获取index的方法

zhongjh

关注

阅读 87

2022-07-13


方法一 使用 .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"

精彩评论(0)

0 0 举报