简体   繁体   English

Javascript 是否具有类似于 Java 的增强的 for 循环语法

[英]Does Javascript have an enhanced for loop syntax similar to Java's

I am wondering if JavaScript has an enhanced for loop syntax that allows you to iterate over arrays.我想知道 JavaScript 是否具有增强的 for 循环语法,允许您遍历数组。 For example, in Java, you can simply do the following:例如,在 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?有没有办法在 JavaScript 中做到这一点? Or do I have to use array.length and use standard for loop syntax as below?或者我必须使用array.length并使用标准的循环语法,如下所示?

var array = "hello there my friend".split(" ");

for (i=0;i<array.length;i++){
    document.write(array[i]);
}

JavaScript has a foreach -style loop ( for (x in a) ), but it is extremely bad coding practice to use it on an Array . JavaScript 有一个foreach风格的循环( for (x in a) ),但是在Array上使用它是非常糟糕的编码实践。 Basically, the array.length approach is correct.基本上, array.length方法是正确的。 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 中使用a.forEach(fn)方法,但不能保证在所有浏览器中都存在它 - 而且它比array.length方法慢。

EDIT 2017 : "We'll see how it goes", indeed.编辑 2017 年:确实,“我们会看到进展如何”。 In most engines now, .forEach() is now as fast or faster than for(;;) , as long as the function is inline, ie arr.forEach(function() { ... }) is fast, foo = function() { ... }; arr.forEach(foo)现在在大多数引擎中, .forEach()现在与for(;;)一样快或更快,只要函数是内联的,即arr.forEach(function() { ... })很快, foo = function() { ... }; arr.forEach(foo) foo = function() { ... }; arr.forEach(foo) might not be. foo = function() { ... }; arr.forEach(foo)可能不是。 One might think that the two should be identical, but the first is easier for the compiler to optimise than the second.有人可能认为两者应该是相同的,但第一个编译器比第二个更容易优化。

Belated EDIT 2020 : There is now for (const item of iterable) , which solves the downsides of using for (item in iterable) .迟来的 2020 年编辑:现在for (const item of iterable)解决了使用for (item in iterable)的缺点。

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 .详细信息位于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".如果您担心浏览器可能不支持此功能,您可以使用他们在“兼容性”下列出的(希望缩小的)实现版本自己添加它。

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:这有点过时了,但这是我几年前从 Mozilla 页面派生的forEach的缩小兼容性版本:

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 .我有一个名为common.js的文件,我在我的所有页面上使用并包含该文件以包含此文件,以及 JavaScript 1.6 中引入的所有其他“Array extras”,如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.) (我一直想让它更新并发布以供公众使用。)

This may not be the fastest approach (see http://jsperf.com/for-vs-foreach/15 for 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 引擎改进,看看这种差异有多少会被优化掉,这将是非常有趣的。 :-) :-)

In ES2015(ES6), you can use the for-of loop.在 ES2015(ES6) 中,您可以使用for-of循环。 It's supported in most browser with the exception of IE.除 IE 外,大多数浏览器都支持它。

let array = [10, 20, 30];

for (let value of array) {
  console.log(value);
}

See the Mozilla explanation here 在此处查看 Mozilla 说明

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.在这种情况下, s是键(索引),而不是值。 You also need to use hasOwnProperty because in loops though the object's prototype also.您还需要使用hasOwnProperty因为in循环中,尽管对象的prototype也是如此。

for(s in array){
    if(array.hasOwnProperty(s)){
        console.log(array[s]);
    }
}

EDIT: As @Amadan pointed out, hasOwnProperty does iterate properties when they're added like this: array.test = function(){} .编辑:正如@Amadan 所指出的, hasOwnProperty在像这样添加时迭代属性: array.test = function(){} I suggest not using for...in .我建议不要使用for...in

EDIT2: If your using a modern web browser (anything that isn't IE < 9), you can use Array.forEach ). EDIT2:如果您使用现代网络浏览器(任何不是 IE < 9 的浏览器),您可以使用Array.forEach @ziesemer points out that Mozilla has a shim for this if you need to support IE < 9. @ziesemer 指出,如果您需要支持 IE < 9, Mozilla 有一个垫片

array.forEach(function(s){
    console.log(s);
});

NOTE: Personally I use jQuery for my JavaScript projects, and I use $.each .注意:我个人在 JavaScript 项目中使用jQuery ,并使用$.each

$.each(array, function(i,s){
    console.log(s);
});

There's the "forEach" method on the Array prototype in newer JavaScript engines.在较新的 JavaScript 引擎中,Array 原型上有“forEach”方法。 Some libraries extend the prototype themselves with a similar method.一些库使用类似的方法扩展原型本身。

Try this:试试这个:

 var errorList = new Array();
 errorList.push("e1");
 errorList.push("e2");
      
 for (var indx in errorList) {
     alert(errorList[indx]);
 }
x = [1,2,3];
for (i in x) {
  console.log(i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM