在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中做同样的事情吗?
当前回答
有一种方法可以只迭代自己的对象财产,而不包括原型的属性:
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>
for(myStringArray的常量){
(直接回答你的问题:现在你可以了!)
大多数其他答案都是正确的,但他们没有提到(截至本文撰写之时)ECMAScript 6 2015正在为执行迭代带来一种新的机制。。循环的。
这种新语法是在JavaScript中迭代数组的最优雅的方式(只要不需要迭代索引)。
它目前可与Firefox 13+、Chrome 37+一起使用,并且不能与其他浏览器一起使用(请参阅下面的浏览器兼容性)。幸运的是,我们有JavaScript编译器(如Babel),允许我们今天使用下一代功能。
它也适用于Node.js(我在0.12.0版本上测试过它)。
迭代数组
// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
console.log(letter);
}
迭代对象数组
const band = [
{firstName : 'John', lastName: 'Lennon'},
{firstName : 'Paul', lastName: 'McCartney'}
];
for(const member of band){
console.log(member.firstName + ' ' + member.lastName);
}
循环发电机:
(示例摘自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
function* fibonacci() { // A generator function
let [prev, curr] = [1, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (const n of fibonacci()) {
console.log(n);
// Truncate the sequence at 1000
if (n >= 1000) {
break;
}
}
兼容性表:http://kangax.github.io/compat-table/es6/#test-用于。。第页,共页
规范:http://wiki.ecmascript.org/doku.php?id=harmony:iterators
}
深奥的
让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对于中等阵列的示例结果:
有一种方法可以在循环中的隐式作用域很小的情况下实现,并去掉额外的变量。
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等迭代器方法。
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。