1

My Code:

<script type="text/javascript">
for each ( var movie in ['Endhiran The Robot','Shivaji The Boss','Anbulla Rajinikanth'] )
    document.writeln(movies + "<br/>");
</script>

In Firefox, I am getting the output as

Endhiran The Robot
Shivaji The Boss
Anbulla Rajinikanth

But in IE9 and Chrome Version 23.0.1271.95 m, for each is not working and nothing is written on the document

Earth
  • 3,477
  • 6
  • 37
  • 78
  • `for each` should be just `for` – Tim Büthe Dec 11 '12 at 13:03
  • btw, the var `movies` should be `movie`, right? and you should not use `document.writeln`/`document.write` at all – Tim Büthe Dec 11 '12 at 13:05
  • @TimBüthe, Thanks. I will be editing and change to `movie`. One doubt, I used `for` alone instead of `for each` but the `output` I am getting as `0,1,2` instead of those `movie names` – Earth Dec 11 '12 at 13:06
  • Yeah, right, that iterates over the index, forgot that. I would suggest to just go with Julien Royer's answer. – Tim Büthe Dec 11 '12 at 13:13
  • @TimBüthe, Thanks. I am going with the Julien Royer's answer. – Earth Dec 11 '12 at 13:15

2 Answers2

4

The for each construction is an extension to the ECMAScript language; it is defined in the E4X specification which is not widely supported.

I think that only Firefox supports it in the HTML scripting microcosm, and it has been deprecated: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for_each...in

To iterate over an array, you can use a plain for loop:

var movies = ['Endhiran The Robot', 'Shivaji The Boss', 'Anbulla Rajinikanth'];
for (var i = 0; i < movies.length; ++i) {
  document.writeln(movies[i] + "<br/>");
}
Julien Royer
  • 1,419
  • 1
  • 14
  • 27
3

There is no for each in JavaScript, that was a non-standard extension.

There is the new ES5 forEach function, which is well supported in modern browsers although of course not in older ones:

['Endhiran The Robot','Shivaji The Boss','Anbulla Rajinikanth'].forEach(function(movie) {
    document.writeln(movie + "<br/>");
});

Several other options over in this other answer here on Stack Overflow. (The question mentions jQuery, but the answer covers both plain JavaScript and jQuery options.)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875