假设我想循环整个数组来访问每个元素。使用 for 循环、for...in 循环或 for...of 循环是 JavaScript 开发人员的标准做法吗?
例如:
var myArray = ["apples", "oranges", "pears"];
for循环
for (var index = 0; index < myArray.length; index++)
console.log(myArray[index]);
For...in 循环
for (var index in myArray)
console.log(myArray[index]);
For...of 循环
for (var element of myArray)
console.log(element);
最佳答案
forEach
应该是可行的方法,作为 Array.prototype 函数的一部分。
For loop
for (var index = 0; index < myArray.length; index++) console.log(myArray[index])
如果我必须选择以上其中之一,长度以上的普通 for 循环是最优选的。
For...in loop
for (var index in myArray) console.log(myArray[index]);
您应该不惜一切代价避免这种情况!将对象与数组混合使用是不好的做法。您可能会因不需要的元素而遇到错误的迭代
关于javascript - 迭代整个数组的标准 JavaScript 实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33200457/