你會用哪些JavaScript循環遍歷

總結JavaScript中的循環遍歷定義一個數組和對象

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

for()

經常用來遍歷數組元素

遍歷值爲數組元素索引

or (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()

用來遍歷數組元素

第一個參數爲數組元素,第二個參數爲數組元素索引,第三個參數爲數組本身(可選)

沒有返回值

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 數組值
}

當我們給數組添加一個屬性name

arr.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

文章同步發佈: https://www.geek-share.com/detail/2755529958.html

參考文章:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章