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

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

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


当前回答

var x = [4, 5, 6];
for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
    console.log(i,j);
}

干净多了。。。

其他回答

当然,这是低效的,很多人都鄙视它,但它是最接近上述的一种:

var myStringArray = ["Hello","World"];
myStringArray.forEach(function(f){
    // Do something
})

阵列循环:

for(var i = 0; i < things.length; i++){
    var thing = things[i];
    console.log(thing);
}

对象循环:

for(var prop in obj){
    var propValue = obj[prop];
    console.log(propValue);
}

阵列迭代有4种方式:

// 1: for

for (let i = 0; i < arr.length; ++i) {
  console.log(arr[i]);
}

// 2: forEach

arr.forEach((v, i) => console.log(v));

// 3: for in

for (let i in arr) {
  console.log(arr[i]);
}

// 4: for of

for (const v of arr) {
  console.log(v);
}

总结:1和3个解决方案创建额外的变量,2-创建额外的函数上下文。最好的方式是第四位-“for of”。

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());}

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

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