es6 for of怎么获取index
1 回答
ibeautiful
TA贡献1993条经验 获得超6个赞
如果是 Map 的 for ... of 就比较简单:
| 123 | for ( const [ key, value ] of map ) { console.log( key, value );} |
但是你问的应该是数组。
数组的 for ... of 获取不了 index,你需要用 forEach
| 1234 | var arr = [ 'a', 'b', 'c' ];arr.forEach( ( item, i ) => { console.log( item, i );} ); |
但是其实也可以把 Array 想办法转成 Map,
| 1 | new Map( arr.map( ( item, i ) => [ i, item ] ) ) |
在一行代码里面实现for ... of:
| 1234567 | var arr = [ 'a', 'b', 'c' ]; for( let [ i, item ] of new Map( arr.map( ( item, i ) => [ i, item ] ) ) ) { console.log( i, item ); } |
- 1 回答
- 0 关注
- 15086 浏览
添加回答
举报
0/150
提交
取消
