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

前端 未结 4 1617
孤独总比滥情好
孤独总比滥情好 2020-12-19 05:16

Python 3.6:

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

gives

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

Ne

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-19 06:10

    There isn't anything so lovely in Javascript. To the best of my knowledge, you need to create a new Array and use .fill() to make each element something other than undefined. Then you can use .map and return/work with the array index rather than the value. Something like this:

    console.log((new Array(5)).fill(0).map((x,i) => `Cat ${i}`))

    You may find generators useful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Generator_comprehensions

提交回复
热议问题