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

前端 未结 4 1611
孤独总比滥情好
孤独总比滥情好 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 05:59

    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; }) )

    0 讨论(0)
  • 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"]
    
    0 讨论(0)
  • 2020-12-19 06:05

    Array comprehension in JS was proposed for ES2016, but never made it to the final release. Firefox supported comprehensions for a time, but the support was dropped in later versions.

    You can use Array#from to get something close to comprehension.

    const result = Array.from({ length: 5 }, (_, k) => `Cat #${k}`);
    
    console.log(result);

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题