在Java中,可以使用for循环遍历数组中的对象,如下所示:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
我可以在JavaScript中做同样的事情吗?
在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)
其他回答
如果您想使用jQuery,它的文档中有一个很好的示例:
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
例如,我在Firefox控制台中使用了:
[].forEach.call(document.getElementsByTagName('pre'), function(e){
console.log(e);
})
您可以使用querySelectorAll获得相同的结果
document.querySelectorAll('pre').forEach((e)=>{console.log(e.textContent);})<pre>文本1</pre><pre>文本2</pre><pre>文本3</pre>
它不是100%相同,但相似:
var myStringArray=['Hello','World'];//数组使用[]而不是{}for(myStringArray中的var i){console.log(i+'->'+myStringArray[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)
深奥的
让a=[“你好”,“世界”];while(a.length){console.log(a.shift());}
性能测试
今天(2022-11-13),我在Chrome 107、Safari 15.2和Firefox 106上对选定的解决方案进行了测试。
结论
解决方案C和D在所有阵列的所有浏览器上都是快速或最快的。解决方案A和B在所有阵列的所有浏览器上都是最慢的
后果
细节
我执行3项测试:
small-用于2元素数组(如OP)-可以在此处运行中等-用于10K元素阵列-您可以在这里运行大-对于100K元素数组-您可以在这里运行
下面的代码段显示了测试中使用的代码。
函数A(A){设r=0;而(a.length)r+=a.shift().length;返回r;}函数B(a){设r=0;对于(i in a)r+=a[i]长度;返回r;}函数C(a){设r=0;对于(a的x)r+=x.length;返回r;}函数D(a){设r=0;对于(i=0;i<a.length;++i)r+=a[i].length;返回r;}函数E(a){设r=0;a.对于每个(x=>r+=x.length);返回r;}let arr=[“你好”,“世界!”];[A,B,C,D,E].forEach(f=>console.log(`${f.name}:${f([…arr])}`))
以下是Chrome对于中等阵列的示例结果: