0
点赞
收藏
分享

微信扫一扫

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


方法一 使用 .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 条评论