在JavaScript中遍历数组(for each循环)

5654

如何使用JavaScript循环遍历数组中的所有条目?


使用 for...of 循环。请参阅 https://www.w3schools.com/JS/js_loop_forof.asp。 - user19690494
与“如何在JavaScript中循环遍历数组”几乎相同,但略微更为通用的内容。 - outis
41个回答

7
如果你想使用forEach(),它会像这样 -
theArray.forEach ( element => {
    console.log(element);
});

如果你想使用 for(),它会像这样 -
for(let idx = 0; idx < theArray.length; idx++){
    let element = theArray[idx];
    console.log(element);
}

5
如果您有一个巨大的数组,应该使用迭代器来提高一些效率。迭代器是某些JavaScript集合(如MapSetStringArray)的属性。甚至,for..of在底层使用迭代器
迭代器通过让您像流一样逐个消耗列表中的项来提高效率。迭代器之所以特殊,是因为它如何遍历集合。其他循环需要预先加载整个集合才能迭代它,而迭代器只需要知道集合中的当前位置。
通过调用迭代器的next方法,您可以访问当前项。下一个方法将返回当前项的和一个布尔值,指示您是否已经到达了集合的末尾。以下是从数组创建迭代器的示例。
使用values()方法将常规数组转换为迭代器,如下所示:

    const myArr = [2,3,4]

let it = myArr.values();

console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());

你也可以使用 Symbol.iterator 将常规数组转换为迭代器,如下所示:

const myArr = [2,3,4]

let it = myArr[Symbol.iterator]();

console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());

你也可以将常规的数组转换为迭代器,方法如下:

let myArr = [8, 10, 12];

function makeIterator(array) {
    var nextIndex = 0;
    
    return {
       next: function() {
           return nextIndex < array.length ?
               {value: array[nextIndex++], done: false} :
               {done: true};
       }
    };
};

var it = makeIterator(myArr);

console.log(it.next().value);   // {value: 8, done: false}
console.log(it.next().value);   // {value: 10, done: false}
console.log(it.next().value);   // {value: 12, done: false}
console.log(it.next().value);   // {value: undefined, done: true}

注意:

  • 迭代器的性质是可耗尽的。
  • 默认情况下,对象不是iterable。在这种情况下,请使用for..in,因为它不使用值而使用键。

您可以在此处阅读有关iteration protocol的更多信息。


5

您可以使用:

  1. ForEach

    theArray.forEach(function (array, index) {
        console.log(index);
        console.log(array);
    });
    
  2. for

    for(var i=0; i<theArray.length; i++) {
        console.log(i)
    }
    
  3. map

    theArray.map(x => console.log(x));
    
  4. map

    theArray.filter(x => console.log(x));
    

还有很多其他的迭代方式。


3
假设我们有一个学科数组:
let ddl = new Array();
if (subjects) {
    subjects.forEach(function (s) {ddl.push({"id": s.id, "label": s.name});});
}

需要解释一下。例如,什么是想法/要点?来自帮助中心:“始终解释为什么您提出的解决方案是合适的以及它如何工作”。请通过编辑(更改)您的答案进行回复,而不是在此处进行评论(不包括“编辑:”,“更新:”或类似内容-答案应该看起来像今天写的)。 - Peter Mortensen

3

我认为for/of是正确的做法:

const arr = ['a', 'b', 'c'];

for (const v of arr) {
  console.log(v); // Prints "a", "b", "c"
}

  • for/in 不同,for/of 在数组上跳过非数字属性。例如,如果你设置了 arr.foo = 'test'for (var v in arr) 将循环遍历 'foo' 键。

  • forEach() 不同,for/of 不会跳过数组中的“空洞”。const arr = ['a',, 'c'] 是有效的 JavaScript 代码,只是第二个元素是一个“空洞”。该数组在功能上等同于 ['a', undefined, 'c']

你可以在这篇关于 for/offorEach() 的博客文章中阅读更多信息。


2
如果您想以函数式的方式保留您的代码,请使用map:
theArray.map(instance => do_something);

以这种方式,您将生成一个新数组用于未来操作,并跳过任何不希望的副作用。翻译成中文:通过这种方式,您将生成一个新的数组来进行未来的操作,并且将跳过任何不必要的负面影响。

1

// Looping through arrays using the foreach ECMAScript 6 way

var data = new Array(1, 2, 3, 4, 5);
data.forEach((val,index) => {
    console.log("index: ", index); // Index
    console.log("value: ", val); // Value
});


-1
var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
    console.log("Index" + index);
    console.log("Element" + item);
})

-1

我喜欢这样做。

foreach

const arr = ["apple", "banana", "orange", "pear", "grape"];

arr.forEach(function(element) {
  console.log(element);
});

for..of

const arr = ["apple", "banana", "orange", "pear", "grape"];

for (const element of arr) {
  console.log(element);
}

-2

Mozilla文档

/* Get all forms */
document.querySelectorAll( "form" ).forEach( form => {

  /* For each form, add the onsubmit event */
  form.addEventListener( "submit", event => {
    event.preventDefault(); // Return false

    /* Display it */
    alert(event.target.action);
    console.log(event.target);
  } );

} );
<form action="form1.php" >
  <input type="submit" value="Submit" />
</form>
<form action="form2.php" >
  <input type="submit" value="Submit" />
</form>
<form action="form3.php" >
  <input type="submit" value="Submit" />
</form>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接