ECMAScript 2015 introduced Array.prototype.entries
, which returns index and element from Array.
Version
ECMAScript 2015
Definition
For Of Loop
let data = ['Sam', 'Kevin', 'Jimmy']
for (let [i, x] of data.entries())
console.log (`${i}: ${x}`)
entries
returns Array Iterator, we can use Array Destructuring to destructure it to get index and element.
map
let data = ['Sam', 'Kevin', 'Jimmy']
let f = a => Array.from (a.entries ())
.map (([i, x]) => `${i}: ${x}`)
f (data) // ?
entries
return Array Iterator, not Array, so we can’t usemap
afterentries
- We have to use
Array.from
to transform Array Iterator to Nested Array, and then we can usemap
Conclusion
entries
return Array Iterator, not Nested Array, so we have to useArray.from
to transform Array Iterator to Nested Array to usemap