Javascript 是否具有类似于 Java 的增强的 for 循环语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8681593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Javascript have an enhanced for loop syntax similar to Java's
提问by ewok
I am wondering if JavaScript has an enhanced for loop syntax that allows you to iterate over arrays. For example, in Java, you can simply do the following:
我想知道 JavaScript 是否具有增强的 for 循环语法,允许您遍历数组。例如,在 Java 中,您可以简单地执行以下操作:
String[] array = "hello there my friend".split(" ");
for (String s : array){
System.out.println(s);
}
output is:
输出是:
hello
there
my
friend
Is there a way to do this in JavaScript? Or do I have to use array.length
and use standard for loop syntax as below?
有没有办法在 JavaScript 中做到这一点?或者我是否必须使用array.length
和使用标准 for 循环语法如下?
var array = "hello there my friend".split(" ");
for (i=0;i<array.length;i++){
document.write(array[i]);
}
采纳答案by Amadan
JavaScript has a foreach
-style loop (for (x in a)
), but it is extremely bad coding practice to use it on an Array
. Basically, the array.length
approach is correct. There is also a a.forEach(fn)
method in newer JavaScripts you can use, but it is not guaranteed to be present in all browsers - and it's slower than the array.length
way.
JavaScript 有一个foreach
样式循环 ( for (x in a)
),但在Array
. 基本上,这个array.length
方法是正确的。a.forEach(fn)
您还可以使用较新的 JavaScript 中的一种方法,但不能保证在所有浏览器中都存在它 - 并且它比array.length
方法慢。
EDIT 2017: "We'll see how it goes", indeed. In most engines now, .forEach()
is now as fast or faster than for(;;)
, as long as the function is inline, i.e. arr.forEach(function() { ... })
is fast, foo = function() { ... }; arr.forEach(foo)
might not be. One might think that the two should be identical, but the first is easier for the compiler to optimise than the second.
编辑 2017 年:确实,“我们会看到进展如何”。在现在的大多数引擎中,只要函数是内联的,即快速,现在可能.forEach()
与 一样快或更快。有人可能认为两者应该是相同的,但第一个编译器比第二个更容易优化。for(;;)
arr.forEach(function() { ... })
foo = function() { ... }; arr.forEach(foo)
回答by ziesemer
Using the latest versions of JavaScript available to most modern browsers, you can do this:
使用适用于大多数现代浏览器的最新版本的 JavaScript,您可以执行以下操作:
array.forEach(function(x){
document.write(x);
});
Details are at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach. If you're worried that a browser may not have support for this, you can add it yourself, using a (hopefully minified) version of the implementation that they have listed under "Compatibility".
详细信息位于https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach。如果您担心浏览器可能不支持此功能,您可以使用他们在“兼容性”下列出的(希望缩小的)实现版本自己添加它。
This is a bit outdated, but this is a minified compatibility version of forEach
that I derived from Mozilla's page a few years ago:
这有点过时了,但这是forEach
我几年前从 Mozilla 页面导出的缩小的兼容性版本:
if(!Array.prototype.forEach){Array.prototype.forEach=function(b){if(typeof b!="function"){throw new TypeError()}var a=this.length,d=arguments[1],c;for(c=0;c<a;c++){if(c in this){b.call(d,this[c],c,this)}}}};
I've never run into any issues with this, but the implementation on Mozilla's page has since been expanded with some additional checks and code to make it compatible with ECMA-262, Edition 5, 15.4.4.18.
我从来没有遇到过任何问题,但是 Mozilla 页面上的实现已经通过一些额外的检查和代码进行了扩展,以使其与 ECMA-262,第 5 版,15.4.4.18 兼容。
I have a file called common.js
that I use and include on all of my pages to include this, as well as all of the other "Array extras" that were introduced with JavaScript 1.6, as listed at https://developer.mozilla.org/en/JavaScript/New_in_JavaScript/1.6#Array_extras. (I've been meaning to get this updated and published for public use.)
我有一个名为的文件common.js
,我在所有页面上使用并包含该文件以包含此文件,以及 JavaScript 1.6 中引入的所有其他“数组附加项”,如https://developer.mozilla.org/所列en/JavaScript/New_in_JavaScript/1.6#Array_extras。(我一直想让它更新并发布以供公众使用。)
This may not be the fastest approach (see http://jsperf.com/for-vs-foreach/15for some specifics - thanks for the link, Amadan) - but there is something to be said for conciseness and maintainability, etc. Additionally, it'll be very interesting to see how much of this disparity is optimized away by further JavaScript engine improvements over the next few months and years. :-)
这可能不是最快的方法(有关某些细节,请参阅http://jsperf.com/for-vs-foreach/15- 感谢 Amadan 提供的链接) - 但对于简洁性和可维护性等,有一些话要说。此外,在接下来的几个月和几年中,通过进一步的 JavaScript 引擎改进,看看这种差异有多少会被优化掉,这将是非常有趣的。:-)
回答by CaseyC
In ES2015(ES6), you can use the for-of
loop. It's supported in most browser with the exception of IE.
在 ES2015(ES6) 中,您可以使用for-of
循环。除 IE 外,大多数浏览器都支持它。
let array = [10, 20, 30];
for (let value of array) {
console.log(value);
}
回答by Rocket Hazmat
You can do for(s in array)
, but be careful, it's not the same as a foreach
.
您可以这样做for(s in array)
,但要小心,它与foreach
.
In this case s
is the key (index), not the value. You also need to use hasOwnProperty
because in
loops though the object's prototype
also.
在这种情况下s
是键(索引),而不是值。您还需要使用hasOwnProperty
因为in
对象prototype
也循环。
for(s in array){
if(array.hasOwnProperty(s)){
console.log(array[s]);
}
}
EDIT: As @Amadan pointed out, hasOwnProperty
doesiterate properties when they're added like this: array.test = function(){}
. I suggest notusing for...in
.
编辑:由于@Amadan指出,hasOwnProperty
确实当他们加入这样的迭代特性:array.test = function(){}
。我建议不要使用for...in
.
EDIT2: If your using a modern web browser (anything that isn't IE < 9), you can use Array.forEach
). @ziesemer points out that Mozilla has a shimfor this if you need to support IE < 9.
EDIT2:如果您使用现代网络浏览器(任何不是 IE < 9 的浏览器),您可以使用Array.forEach
)。@ziesemer 指出,如果您需要支持 IE < 9 ,Mozilla 有一个垫片。
array.forEach(function(s){
console.log(s);
});
NOTE: Personally I use jQueryfor my JavaScript projects, and I use $.each
.
注意:我个人在 JavaScript 项目中使用jQuery,我使用$.each
.
$.each(array, function(i,s){
console.log(s);
});
回答by Pointy
There's the "forEach" method on the Array prototype in newer JavaScript engines. Some libraries extend the prototype themselves with a similar method.
在较新的 JavaScript 引擎中,Array 原型上有“forEach”方法。一些库使用类似的方法扩展原型本身。
回答by Chris Lohfink
x = [1,2,3];
for (i in x) {
console.log(i);
}
回答by shanika yrs
Try this,
尝试这个,
var errorList = new Array();
errorList.push("e1");
errorList.push("e2");
for (var indx in errorList){
alert(errorList[indx]);
}