在Java中,可以使用for循环遍历数组中的对象,如下所示:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}

我可以在JavaScript中做同样的事情吗?


当前回答

它不是100%相同,但相似:

var myStringArray=['Hello','World'];//数组使用[]而不是{}for(myStringArray中的var i){console.log(i+'->'+myStringArray[i]);//我是索引/键,而不是项目}

其他回答

嗯,这个怎么样:

for (var key in myStringArray) {
    console.log(myStringArray[key]);
}

6种不同的方法循环遍历阵列

可以通过许多不同的方法循环遍历数组。我从上到下整理了我最喜欢的6种方法。

1.使用for循环

当它只是在数组中循环时,for循环是我的首选。

让数组=[1,2,3,4,5];for(设i=0;i<array.length;i++){console.log(array[i]);}

2.使用forEach循环

forEach循环是一种在数组中循环的现代方式。此外,它还提供了对阵列和元素的更多灵活性和控制。

让数组=[1,2,3,4,5];array.forEach((元素)=>{console.log(元素);});

3.用于。。。属于

对于of循环允许您直接访问数组元素。

让数组=[1,2,3,4,5];for(数组的let元素){console.log(元素);}

4.用于。。。在回路中

对于中提供了一个键,您可以使用该键访问数组元素。

让数组=[1,2,3,4,5];for(数组中的let索引){console.log(array[index]);}

5.使用while循环

而loop也可以用于循环通过阵列。

让数组=[1,2,3,4,5];let length=array.length;而(长度>0){console.log(array[array.length-length]);长度--;}

6.使用do…while循环

同样,我使用do…while循环

让数组=[1,2,3,4,5];let length=array.length;做{console.log(array[array.length-length]);长度--;}而(长度>0)

有一种方法可以在循环中的隐式作用域很小的情况下实现,并去掉额外的变量。

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等迭代器方法。

正式的(也许是旧的)方式是Array.protocol.forEach(…):

var arr = ["apple", "banana", "cherry", "mango"];
arr.forEach(function(item, index, _) {
   console.log("[" + index + "] = '" + item + "'");
});

您可以使用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。