Domanda

I've been reading up on the newer features of Javascript and noticed the Array Comprehension stuff. I've tried this in my current project, but it seems Visual Studio doesn't like the syntax. Am I doing it wrong?

var destArray = [{propOne: val, propTwo:val} for (val of sourceArray)];
È stato utile?

Soluzione

This is in fact part of the upcoming ES2016 specification, not ECMAScript 5 (your question was originally tagged with ).

According to this and the MDN documentation, you actually need to place the for section at the beginning, not the end:

var destArray = [ for (val of sourceArray) { propOne: val, propTwo: val } ];

Just like other languages such as Python, you can also include multiple for loops and if statements:

var numbers = [1,2,3,4,5,6,7,8,9,10];
var even = [ for (val of numbers) if (val % 2 === 0) val ];

Note that most text editors and IDEs don't support syntax highlighting for these new language features yet, so highlighting/colouring may look odd until more support comes in the future.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top