在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中做同样的事情吗?
当前回答
最优雅快捷的方式
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 someArray = ["some", "example", "array"];
您可以在不访问长度属性的情况下对其进行循环:
for (var i=0, item; item=someArray[i]; i++) {
// item is "some", then "example", then "array"
// i is the index of item in the array
alert("someArray[" + i + "]: " + item);
}
请参阅本JsFidle演示:http://jsfiddle.net/prvzk/
这只适用于非稀疏阵列。这意味着数组中的每个索引实际上都有一个值。然而,我发现在实践中我几乎从未在JavaScript中使用过稀疏数组。。。在这种情况下,通常更容易将对象用作映射/哈希表。如果您有一个稀疏数组,并且希望在0上循环。。length-1,您需要for(vari=0;i<someArray.length;++i)构造,但仍需要在循环内使用if来检查当前索引处的元素是否已实际定义。
此外,正如CMS在下面的注释中所提到的,您只能在不包含任何错误值的数组上使用它。示例中的字符串数组是有效的,但如果您有空字符串或0或NaN等数字,则循环将提前中断。在实践中,这对我来说几乎从来都不是问题,但这是一件需要记住的事情,这使得在使用它之前,这是一个需要考虑的循环……这可能会使某些人失去资格:)
我喜欢这个循环的地方是:
写起来很短无需访问(更不用说缓存)长度属性要访问的项在循环中自动定义你选择的名字下的身体。与array.push和array.please非常自然地结合,使用列表/堆栈等数组
这种方法之所以有效,是因为数组规范规定,当您从索引中读取一个项>=数组长度时,它将返回undefined。当你写到这样的位置时,它实际上会更新长度。
对我来说,这个构造最接近于我喜欢的Java5语法:
for (String item : someArray) {
}
…还有一个额外的好处,那就是了解循环内的当前索引
您可以使用map,这是一种函数式编程技术,也可以在Python和Haskell等其他语言中使用。
[1,2,3,4].map( function(item) {
alert(item);
})
一般语法为:
array.map(func)
一般来说,func需要一个参数,这是数组的一个项。但在JavaScript的情况下,它可以接受第二个参数,即项目的索引,以及第三个参数,也就是数组本身。
array.map的返回值是另一个数组,因此可以这样使用:
var x = [1,2,3,4].map( function(item) {return item * 10;});
现在x是[10,20,30,40]。
您不必内联编写函数。它可能是一个单独的功能。
var item_processor = function(item) {
// Do something complicated to an item
}
new_list = my_list.map(item_processor);
这相当于:
for (item in my_list) {item_processor(item);}
除非你没有得到new_list。
如果你想用一种简洁的方式写一个快速循环,你可以反过来迭代:
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中删除项。
有一种方法可以只迭代自己的对象财产,而不包括原型的属性:
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。
例如,我在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>