在前後端開發中,我們常常會操作集合類型的數據,而JS遍歷List無疑是其中最為常見的操作之一。本文將從多個方面對JS遍歷List做詳細的闡述。
一、基本遍歷方式
const list = ['a', 'b', 'c'];
for (let i = 0; i<list.length; i++) {
console.log(list[i]);
}
上述代碼中使用了for循環遍歷List,中間通過i變數索引每一個元素進行操作。這種方式是JS最基本的遍歷方式,能夠滿足簡單List的遍歷需求。
二、forEach遍歷方式
const list = ['a', 'b', 'c'];
list.forEach(item => {
console.log(item);
});
forEach是一種遍曆數組的方式,可以接收一個函數作為參數。該遍歷方式具有以下特點:
- 無需使用循環變數,簡化代碼。
- forEach不能像普通的循環一樣在中途返回。
- 無法在forEach內部使用break表達式,需要使用return。
- 不會改變原數組的值,僅用於遍歷。
三、for…in 和 for…of 遍歷方式
const list = ['a', 'b', 'c'];
for (const index in list) {
console.log(list[index]);
}
for (const item of list) {
console.log(item);
}
兩種方式均可以遍歷List,但有以下區別:
- for…in遍歷出的是List的index,for…of遍歷出的是List的value。
- for…in遍歷對象屬性時輸出的順序不會按照對象屬性的順序輸出,而for…of遍曆數組時輸出的順序會按照數組元素順序輸出。
- for…in可以遍歷對象屬性,而for…of不能。
四、map遍歷方式
const list = ['a', 'b', 'c'];
const newList = list.map(item => {
return item.toUpperCase();
});
console.log(newList); // ['A', 'B', 'C']
map可以將原數組映射為一個新的數組,具有以下特點:
- 通過傳入一個函數,並且該函數返回一個新的值,來重新生成一個新的數組。
- 可以使用filter過濾一些滿足特定條件的元素。
五、reduce遍歷方式
const list = [1, 2, 3, 4, 5];
const result = list.reduce((total, num) => {
return total + num;
}, 0);
console.log(result); // 15
reduce可以通過累加計算得到一個新值,具有以下特點:
- 可以通過傳入一個函數來對數組元素依次累加,得到一個新的值。
- 可以通過第二個參數,指定初始值。
六、多維List遍歷
const list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < list[i].length; j++) {
console.log(list[i][j]);
}
}
多維List遍歷可以通過嵌套循環來實現。需要注意的是,內部循環的索引需要使用不同的變數。
七、Iterator遍歷方式
function makeIterator(list) {
let nextIndex = 0;
return {
next() {
if (nextIndex < list.length) {
return {value: list[nextIndex++], done: false};
} else {
return {done: true};
}
}
};
}
const list = ['a', 'b', 'c'];
const it = makeIterator(list);
let result = it.next();
while (!result.done) {
console.log(result.value);
result = it.next();
}
Iterator是ES6推出的一種遍歷方式,具有以下特點:
- 可以自定義數據遍歷。
- 可以定義內部狀態,可以讓遍歷暫停和繼續。
八、async/await實現遍歷
async function asyncForEach(list, callback) {
for (let i = 0; i < list.length; i++) {
await callback(list[i], i, list);
}
}
asyncForEach([1, 2, 3], async(item, index, list) => {
await new Promise(resolve => {
setTimeout(() => {
console.log(item);
resolve();
}, 1000);
});
});
通過async/await實現遍歷具有以下特點:
- 可以將非同步回調同步執行。
- 可以自定義回調函數的同時將非同步代碼注入其中。
結束語
通過以上八種方式,我們可以對JS遍歷List有一個更深入和全面的理解。在開發過程中,我們需要靈活根據實際情況選擇最適合的遍歷方式,提高開發效率。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/238042.html
微信掃一掃
支付寶掃一掃