在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。

其他回答

在JavaScript中,不建议使用for In循环遍历Array,但最好使用for循环,例如:

for(var i=0, len=myArray.length; i < len; i++){}

它也进行了优化(“缓存”数组长度)。如果你想了解更多,请阅读我关于这个主题的帖子。

例如,我在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。

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());}

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

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

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

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