1. 程式人生 > >JavaScript迴圈遍歷你會用哪些?

JavaScript迴圈遍歷你會用哪些?

總結JavaScript中的迴圈遍歷

定義一個數組和物件

const arr = ['a', 'b', 'c', 'd', 'e', 'f'];
const obj = {
    a: 1,
    b: 2,
    c: 3,
    d: 4
}

for()

經常用來遍歷陣列元素遍歷值為陣列元素索引
for (let i = 0, len = arr.length; i < len; i++) {
    console.log(i);            // 0 1 2 3 4 5
    console.log(arr[i]);     // a b c d e f
}

forEach()

用來遍歷陣列元素第一個引數為陣列元素,第二個引數為陣列元素索引,第三個引數為陣列本身(可選)沒有返回值
arr.forEach((item, index) => {
    console.log(item);     // a b c d e f 
    console.log(index);   // 0 1 2 3 4 5
})

map()

用來遍歷陣列元素第一個引數為陣列元素,第二個引數為陣列元素索引,第三個引數為陣列本身(可選)有返回值,返回一個新陣列

every(),some(),filter(),reduce(),reduceRight()不再一一介紹,詳細請看Js中Array方法有哪些?

let arrData = arr.map((item, index) => {
    console.log(item);     // a b c d e f 
    console.log(index);   // 0 1 2 3 4 5
    return item;
})
console.log(arrData);    // ["a", "b", "c", "d", "e", "f"]

for...in

可迴圈物件和陣列,推薦用於迴圈物件
  • 用於迴圈物件時
迴圈值為物件屬性
for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key);           // a b c d  屬性
        console.log(obj[key]);    // 1 2 3 4  屬性值
    }
}
  • 用於遍歷陣列時
值為陣列索引
for (let index in arr) {
    console.log(index);          // 0 1 2 3 4 5 陣列索引
    console.log(arr[index]);   // a b c d e f 陣列值
}

當我們給陣列新增一個屬性namearr.name = '我是自定義的屬性'

for (let index in arr) {
    console.log(index);           // 0 1 2 3 4 5 name (會遍歷出我們自定義的屬性)
    console.log(arr[index]);    // a b c d e f 我是自定義屬性name
}

for...of

可迴圈物件和陣列,推薦用於遍歷陣列
  • 用於遍歷陣列時
遍歷值為陣列元素
for (let value of arr) {
    console.log(value);       // a b c d e f 陣列值
}
  • 用於迴圈物件時
須配合Object.keys()一起使用,直接用於迴圈物件會報錯,不推薦使用for...of迴圈物件迴圈值為物件屬性
for (let value of Object.keys(obj)) {
    console.log(value);    // a b c d 物件屬性
}

總結

  • 用於遍歷陣列元素使用:for(),forEach(),map(),for...of
  • 用於迴圈物件屬性使用:for...in
關於上述迴圈對效能的影響會後續補充

更多內容請關注我的部落格