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

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

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


当前回答

6种不同的方法循环遍历阵列

可以通过许多不同的方法循环遍历数组。我从上到下整理了我最喜欢的6种方法。

1.使用for循环

当它只是在数组中循环时,for循环是我的首选。

让数组=[1,2,3,4,5];for(设i=0;i<array.length;i++){console.log(array[i]);}

2.使用forEach循环

forEach循环是一种在数组中循环的现代方式。此外,它还提供了对阵列和元素的更多灵活性和控制。

让数组=[1,2,3,4,5];array.forEach((元素)=>{console.log(元素);});

3.用于。。。属于

对于of循环允许您直接访问数组元素。

让数组=[1,2,3,4,5];for(数组的let元素){console.log(元素);}

4.用于。。。在回路中

对于中提供了一个键,您可以使用该键访问数组元素。

让数组=[1,2,3,4,5];for(数组中的let索引){console.log(array[index]);}

5.使用while循环

而loop也可以用于循环通过阵列。

让数组=[1,2,3,4,5];let length=array.length;而(长度>0){console.log(array[array.length-length]);长度--;}

6.使用do…while循环

同样,我使用do…while循环

让数组=[1,2,3,4,5];let length=array.length;做{console.log(array[array.length-length]);长度--;}而(长度>0)

其他回答

有一种方法可以在循环中的隐式作用域很小的情况下实现,并去掉额外的变量。

var i = 0,
     item;

// Note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){
    item; // This is the string at the index.
}

或者如果你真的想得到id并有一个真正经典的for循环:

var i = 0,
    len = myStringArray.length; // Cache the length

for ( ; i < len ; i++ ){
    myStringArray[i]; // Don't use this if you plan on changing the length of the array
}

现代浏览器都支持Array原型上的Each、map、reduce、filter等迭代器方法。

考虑一下:

const ITEMS = ['One','Two','Three']
let item=-1

//Then, you get looping with every call of:

ITEMS[item=item==ITEMS.length-1?0:item+1]

在JavaScript中,不建议使用for In循环遍历Array,但最好使用for循环,例如:

for(var i=0, len=myArray.length; i < len; i++){}

它也进行了优化(“缓存”数组长度)。如果你想了解更多,请阅读我关于这个主题的帖子。

6种不同的方法循环遍历阵列

可以通过许多不同的方法循环遍历数组。我从上到下整理了我最喜欢的6种方法。

1.使用for循环

当它只是在数组中循环时,for循环是我的首选。

让数组=[1,2,3,4,5];for(设i=0;i<array.length;i++){console.log(array[i]);}

2.使用forEach循环

forEach循环是一种在数组中循环的现代方式。此外,它还提供了对阵列和元素的更多灵活性和控制。

让数组=[1,2,3,4,5];array.forEach((元素)=>{console.log(元素);});

3.用于。。。属于

对于of循环允许您直接访问数组元素。

让数组=[1,2,3,4,5];for(数组的let元素){console.log(元素);}

4.用于。。。在回路中

对于中提供了一个键,您可以使用该键访问数组元素。

让数组=[1,2,3,4,5];for(数组中的let索引){console.log(array[index]);}

5.使用while循环

而loop也可以用于循环通过阵列。

让数组=[1,2,3,4,5];let length=array.length;而(长度>0){console.log(array[array.length-length]);长度--;}

6.使用do…while循环

同样,我使用do…while循环

让数组=[1,2,3,4,5];let length=array.length;做{console.log(array[array.length-length]);长度--;}而(长度>0)

最好使用顺序for循环:

for (var i = 0; i < myStringArray.length; i++) {
    // Do something
}