What's the equivalent of a list comprehension like this one in ES2016 or greater?

Viewed 4868

Python 3.6:

[f"Cat #{n}" for n in range(5)]

gives

['Cat #0', 'Cat #1', 'Cat #2', 'Cat #3', 'Cat #4']

New to JavaScript, What's the equivalent in new EcmaScript?

4 Answers

console.log( [...Array(5)].map((v, i) => `Cat #${i}`) )

If it has to work in IE too :

console.log( Array.apply(0, Array(5)).map(function(v, i) { return 'Cat #' + i; }) )

Use the combination of Generator and Spread Operator.

ES2015:

[...(function*(){for(let n=0;n<5;)yield'Cat #'+n++})()]

gives

["Cat #0", "Cat #1", "Cat #2", "Cat #3", "Cat #4"]
Related