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

其他回答

优化的方法是缓存数组长度,并使用单变量模式,用一个var关键字初始化所有变量。

var i, max, myStringArray = ["Hello", "World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
    alert(myStringArray[i]);

    // Do something
}

如果迭代的顺序无关紧要,那么您应该尝试反向循环。它是最快的,因为它减少了开销条件测试,并且减少了一个声明:

var i,myStringArray = ["item1","item2"];
for (i =  myStringArray.length; i--) {
    alert(myStringArray[i]);
}

或者使用while循环更好更干净:

var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
   // Do something with fruits[i]
}

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

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

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

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

有多种方法可以在javascript中实现。下面是处理数组的常用方法。

方法1:

const students = ["Arun","Jos","John","Kiran"]
for (var index = 0; index < students.length; index++) {
  console.log(students[index]);
}

方法2:

students.forEach((学生,索引)=>console.log(学生));

方法3:

for (const student of students) {
      console.log(student);
}
  

如果您想使用jQuery,它的文档中有一个很好的示例:

 $.each([ 52, 97 ], function( index, value ) {
      alert( index + ": " + value );
 });