Reputation: 3571
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
Upvotes: 1
Views: 2496
Reputation: 1429
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/>");
}
Upvotes: 4
Reputation: 1075099
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.)
Upvotes: 3