2

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)];
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Stephen Collins
  • 3,523
  • 8
  • 40
  • 61
  • VS is about 5 years behind javascript in the wild; just wait ;) – dandavis Apr 25 '14 at 16:18
  • 1
    @dandavis: I don't think array comprehensions are exactly "in the wild". In fact, does *any* JS engine that's in actual use support them yet? – Matti Virkkunen Apr 27 '14 at 18:19
  • @MattiVirkkunen: i played with them years ago in firefox2: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7#Array_comprehensions_(Merge_into_Array_comprehensions) so yeah, VS just needs to catch up with firefox v2. – dandavis May 01 '14 at 15:05
  • 1
    @dandavis: VS needs to catch up with some obscure feature one specific JavaScript engine used mainly by one browser supports? I don't think so. – Matti Virkkunen May 02 '14 at 08:12

1 Answers1

1

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.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
  • Thanks for the note. It seems the syntax you suggest isn't understood by Chrome, either, so I suppose there's some waiting to do before I can even use this language feature at all. – Stephen Collins Apr 28 '14 at 20:13
  • Yes, it's not currently implemented in browsers yet, though some other sections of ES6 have already been implemented. – Qantas 94 Heavy Apr 30 '14 at 06:34