在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中做同样的事情吗?
当前回答
JavaScript中的数组遍历作弊表
给定一个数组,可以通过以下多种方式之一遍历它。
1.经典for loop
const myArray=['Hello','World'];for(设i=0;i<myArray.length;i++){console.log(myArray[i]);}
2.用于。。。属于
const myArray=['Hello','World'];for(myArray的常量项){console.log(项);}
3.Array.prototype.forEach()
const myArray=['Hello','World'];myArray.forEach(项=>{console.log(项);});
4.while循环
const myArray=['Hello','World'];设i=0;while(i<myArray.length){console.log(myArray[i]);i++;}
5.do…while循环
const myArray=['Hello','World'];设i=0;做{console.log(myArray[i]);i++;}而(i<myArray.length);
6.队列样式
const myArray=['Hello','World'];while(myArray.length){console.log(myArray.shift());}
7.堆栈样式
注:该列表在本页中以相反的方式打印。const myArray=['Hello','World'];while(myArray.length){console.log(myArray.pop());}
其他回答
最好使用顺序for循环:
for (var i = 0; i < myStringArray.length; i++) {
// Do something
}
似乎列出了所有变体,除了lodash的Each:
_.forEach([1, 2], (value) => {
console.log(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中删除项。
例如,我在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>
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。