遍历整个数组的标准JavaScript实践

Standard JavaScript practice for iterating through an entire array?

本文关键字:标准 JavaScript 实践 数组 遍历      更新时间:2023-09-26

假设我想循环遍历整个数组以访问每个元素。JavaScript开发人员使用for循环,for…In循环,或者for…循环?

例如:

var myArray = ["apples", "oranges", "pears"];
For循环

for (var index = 0; index < myArray.length; index++)
    console.log(myArray[index]);

……在循环

for (var index in myArray)
    console.log(myArray[index]);

……循环

for (var element of myArray)
    console.log(element);

forEach应该作为数组的一部分。原型功能。

For循环

for (var index = 0; index < myArray.length; index++)
    console.log(myArray[index])

如果我必须在上面选择一个,长度在上面的香草for循环是最受欢迎的。

……在循环

for (var index in myArray)
    console.log(myArray[index]);

你应该不惜一切代价避免这个 !将用于对象的习惯用法与用于数组的习惯用法混合在一起是不好的做法。您可能会遇到不需要的元素

的错误迭代。
For循环

for (var index = 0; index < myArray.length; index++)
console.log(myArray[index]);

这是数组和跨浏览器的最佳选择!它允许在需要时中断循环,但不允许使用Array.forEach

使用array !

避免这种方法