在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中有多种循环数组的方法。
通用循环:
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。
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。
您可以使用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。
例如,我在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>
var obj = ["one","two","three"];
for(x in obj){
console.log(obj[x]);
}