for each loop is not working in major browsers except firefox

强颜欢笑 提交于 2019-12-13 02:21:34

问题


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


回答1:


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.)




回答2:


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/>");
}


来源:https://stackoverflow.com/questions/13820960/for-each-loop-is-not-working-in-major-browsers-except-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!