Python has a built-in function enumerate
, to get an iterable of (index, item)
pairs.
Does ES6 have an equivalent for an array? What is it?
def elements_with_index(elements):
modified_elements = []
for i, element in enumerate(elements):
modified_elements.append("%d:%s" % (i, element))
return modified_elements
print(elements_with_index(["a","b"]))
#['0:a', '1:b']
ES6 equivalent without enumerate
:
function elements_with_index(elements){
return elements.map(element => elements.indexOf(element) + ':' + element);
}
console.log(elements_with_index(['a','b']))
//[ '0:a', '1:b' ]
Yes there is, check out Array.prototype.entries()
.
const foobar = ['A', 'B', 'C'];
for (const [index, element] of foobar.entries()) {
console.log(index, element);
}