Nodejs中的,除了經典的for循環 , 其實還有幾種好用的循環方式, 并有典型的使用場景。下面來一起看下👇🏻
5種循環用法
- For Loop:這是最常見的循環方式,適用于你知道循環次數的情況。
for (let i = 0; i < 10; i++) {console.log(i);
}
最常見用法,優點是通用,基本上各個語言都有這個寫法。缺點是有些場景使用不方便。
- While Loop:當你不知道循環次數,但知道循環結束的條件時,可以使用 while 循環。
let i = 0;
while (i < 10) {console.log(i);i++;
}
- For…of Loop:這是 ES6 引入的新特性,用于遍歷數組或其他可迭代對象。
const array = [1, 2, 3, 4, 5];
for (const value of array) {console.log(value);
}
這種循環本質屬于迭代遍歷,可用于遍歷可迭代對象(如數組、Map、Set、字符串等)。它直接提供了每個元素的值,而不是索引或鍵名。此外這種遍歷,還可以自定義迭代 內容。
自定義迭代遍歷-示例1:
const iterable = {[Symbol.iterator]() {let i = 1;return {next() {if (i <= 3) {return { value: i++, done: false };}return { value: undefined, done: true };},};},
};for (const value of iterable) {console.log(value);
}
// 1
// 2
// 3
或者換種寫法 ,自定義迭代遍歷-示例2
const iterable = {*[Symbol.iterator]() {yield 1;yield 2;yield 3;},
};for (const value of iterable) {console.log(value);
}
// 1
// 2
// 3
自定義迭代遍歷-示例3: early exiting
const source = [1, 2, 3];const iterator = source[Symbol.iterator]();for (const value of iterator) {console.log(value);if (value === 1) {break;}console.log("This string will not be logged.");
}
// 1// Another loop using the same iterator
// picks up where the last loop left off.
for (const value of iterator) {console.log(value);
}
// 2
// 3// The iterator is used up.
// This loop will execute no iterations.
for (const value of iterator) {console.log(value);
}
// [No output]
可以看到迭代器遍歷,中途中止退出迭代后,下次使用相同迭代器可以從上次中止的位置繼續迭代遍歷。
- Array.prototype.forEach:這是一個數組方法,用于遍歷數組。
const array = [1, 2, 3, 4, 5];
array.forEach((value, index) => {console.log(value);
});
它提供了元素值和索引兩個參數,但不能使用?break
?或?continue
,也不能通過?return
?語句跳出循環。
- For…in Loop:這種循環用于遍歷對象的鍵名。
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {console.log(key, obj[key]);
}
對象友好,這種循環用于遍歷對象的鍵名。它不僅可以遍歷對象自身的屬性,還會遍歷其原型鏈上的屬性(除非屬性被標記為不可枚舉)。
小結
最后小結一下,遍歷數組可以用 for, while, for of, forEach,遍歷對象可以用 for in,如果想自定義遍歷邏輯還可以自定義迭代器。