溫馨提示×

es6數組遍歷的方法是什么

es6
小億
127
2023-11-10 17:41:35
欄目: 編程語言

ES6中數組遍歷的方法有以下幾種:

  1. for…of循環:使用for…of循環可以直接遍歷數組中的每個元素。例如:

    const arr = [1, 2, 3];
    for (const item of arr) {
      console.log(item);
    }
    
  2. forEach()方法:使用forEach()方法可以對數組中的每個元素執行指定的操作。例如:

    const arr = [1, 2, 3];
    arr.forEach(item => {
      console.log(item);
    });
    
  3. map()方法:使用map()方法可以對數組中的每個元素執行指定的操作,并返回一個新的數組。例如:

    const arr = [1, 2, 3];
    const newArr = arr.map(item => item * 2);
    console.log(newArr); // [2, 4, 6]
    
  4. filter()方法:使用filter()方法可以根據指定的條件過濾數組中的元素,并返回一個新的數組。例如:

    const arr = [1, 2, 3, 4, 5];
    const newArr = arr.filter(item => item % 2 === 0);
    console.log(newArr); // [2, 4]
    
  5. reduce()方法:使用reduce()方法可以對數組中的元素進行累加或其他操作,并返回一個結果。例如:

    const arr = [1, 2, 3, 4, 5];
    const sum = arr.reduce((total, item) => total + item, 0);
    console.log(sum); // 15
    

這些方法都是ES6中新增的數組方法,它們提供了更方便、簡潔的方式來遍歷和操作數組。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女