在Java中,可以使用for循环遍历数组中的对象,如下所示:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}

我可以在JavaScript中做同样的事情吗?


当前回答

如果您想使用jQuery,它的文档中有一个很好的示例:

 $.each([ 52, 97 ], function( index, value ) {
      alert( index + ": " + value );
 });

其他回答

JavaScript中的数组遍历作弊表

给定一个数组,可以通过以下多种方式之一遍历它。

1.经典for loop

const myArray=['Hello','World'];for(设i=0;i<myArray.length;i++){console.log(myArray[i]);}

2.用于。。。属于

const myArray=['Hello','World'];for(myArray的常量项){console.log(项);}

3.Array.prototype.forEach()

const myArray=['Hello','World'];myArray.forEach(项=>{console.log(项);});

4.while循环

const myArray=['Hello','World'];设i=0;while(i<myArray.length){console.log(myArray[i]);i++;}

5.do…while循环

const myArray=['Hello','World'];设i=0;做{console.log(myArray[i]);i++;}而(i<myArray.length);

6.队列样式

const myArray=['Hello','World'];while(myArray.length){console.log(myArray.shift());}

7.堆栈样式

注:该列表在本页中以相反的方式打印。const myArray=['Hello','World'];while(myArray.length){console.log(myArray.pop());}

var obj = ["one","two","three"];

for(x in obj){
    console.log(obj[x]);
}

如果有人对Array迭代可用的多种机制的性能方面感兴趣,我准备了以下JSPerf测试:

https://jsperf.com/fastest-array-iterator

结果:

传统的for()迭代器是迄今为止最快的方法,尤其是在缓存数组长度时。

let arr = [1,2,3,4,5];

for(let i=0, size=arr.length; i<size; i++){
    // Do something
}

Array.prototype.forEach()和Array.prototype.map()方法是最慢的近似方法,可能是函数调用开销的结果。

它不是100%相同,但相似:

var myStringArray=['Hello','World'];//数组使用[]而不是{}for(myStringArray中的var i){console.log(i+'->'+myStringArray[i]);//我是索引/键,而不是项目}

我强烈建议使用Undercore.js库。它为您提供了可用于迭代数组/集合的各种函数。

例如:

_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...