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

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

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


当前回答

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

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

其他回答

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

例如:

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

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

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

如果你想用一种简洁的方式写一个快速循环,你可以反过来迭代:

for (var i=myArray.length;i--;){
  var item=myArray[i];
}

这样做的好处是缓存长度(类似于for(var i=0,len=myArray.length;i<len;++i),而不像for(var i=0;i<myArray.long;++i)),同时输入的字符更少。

甚至有些时候,您应该反向迭代,例如在实时NodeList上迭代时,您计划在迭代期间从DOM中删除项。

最优雅快捷的方式

var arr = [1, 2, 3, 1023, 1024];
for (var value; value = arr.pop();) {
    value + 1
}

http://jsperf.com/native-loop-performance/8


编辑(因为我错了)


比较循环遍历100000个项目数组的方法,并每次使用新值执行最小操作。

http://jsben.ch/#/BQhED

准备工作:

<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script>
    Benchmark.prototype.setup = function() {
        // Fake function with minimal action on the value
        var tmp = 0;
        var process = function(value) {
            tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
        };
        
        // Declare the test Array
        var arr = [];
        for (var i = 0; i < 100000; i++)
            arr[i] = i;
    };
</script>

测验:

<a href="http://jsperf.com/native-loop-performance/16" 
   title="http://jsperf.com/native-loop-performance/16"
><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>

深奥的

让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对于中等阵列的示例结果: