What is equivalent to understanding a list like this in ES2016 or higher?

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 is equivalent in the new EcmaScript?

+6
source share
4 answers

The introduction of Array in JS was proposed for ES2016, but never reached the final version. Firefox maintained awareness for some time, but support was removed in later versions.

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

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

There is nothing beautiful in Javascript. As far as I know, 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 index of the array, not the value. Something like that:

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

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

+7
source

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"] 
+2
source

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

If this should work in IE too:

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

Source: https://habr.com/ru/post/1270202/


All Articles