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

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

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


当前回答

JavaScript中有多种循环数组的方法。

通用循环:

var i;
for (i = 0; i < substr.length; ++i) {
    // Do something with `substr[i]`
}

每个ES5:

substr.forEach(function(item) {
    // Do something with `item`
});

jQuery.each:

jQuery.each(substr, function(index, item) {
    // Do something with `item` (or `this` is also `item` if you like)
});

查看此信息以获取详细信息,或者您也可以检查MDN是否在JavaScript中循环遍历数组,并使用jQuery检查每个数组的jQuery。

其他回答

有一种方法可以只迭代自己的对象财产,而不包括原型的属性:

for (var i in array) if (array.hasOwnProperty(i)) {
    // Do something with array[i]
}

但它仍将迭代自定义的财产。

在JavaScript中,任何自定义属性都可以分配给任何对象,包括数组。

如果要在稀疏数组上迭代,应使用for(var i=0;i<array.length;i++)If(i in array)或array.forEach with es5shim。

最优雅快捷的方式

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>

var array=['hai','hello','how','are','you']$(文档).ready(函数(){$('#clickButton').click(函数(){对于(var i=0;i<array.length;i++){警报(阵列[i])}})})<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js“></script><input id=“clickButton”value=“click Me”type=“button”/><div id=“show”></div>

简短回答:是的。你可以这样做:

var myArray = ["element1", "element2", "element3", "element4"];

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

在浏览器控制台中,您可以看到打印的“element1”、“element2”等内容。

简单的单线解决方案:

arr=[“桌子”,“椅子”];//解决方案arr.map((e)=>{控制台日志(e);返回e;});