JS迴圈總結
阿新 • • 發佈:2022-03-26
工作發現,專案中的對於物件、陣列的迴圈,使用的方法各不相同,有forEach
、for in
、for of
、map
以及for
,故對這些迴圈做些總結。
forEach(陣列方法)
特性
- 遍歷的時候更加簡潔,效率和for迴圈相同,不用關係集合下標的問題,減少了出錯的概率。
- 沒有返回值。
- 不能使用break中斷迴圈,不能使用return返回到外層函式。
例項
const array = [1, 2, 3]; let newArray = array.forEach(item => { item+=1; console.log(item);// 2 3 4 }) console.log(array); // [1, 2, 3] console.log(newArray) // undefined
for in
特性
更適合遍歷物件,可以遍歷陣列,但是會有一些侷限性。
例項
for in
的索引為字串型數字,不能直接進行幾何運算
const array = [1, 2, 3];
for(const i in array) {
const res = i + 1;
console.log(res);
}
// 01 11 21
遍歷順序有可能不是按照實際陣列的內部順序,使用for in
會遍歷陣列所有的可列舉屬性,包括原型,如果不想遍歷原型方法和屬性的話,可以在迴圈內部判斷一下,使用hasOwnProperty()
方法可以判斷某屬性是不是該物件的例項屬性
const array = [1, 2, 3]; Array.prototype.a = 123; for (const index in array) { const res = array[index]; console.log(res); } // 1 2 3 123 for (const index in array) { if (array.hasOwnProperty(index)) { const res = array[index]; console.log(res); } } // 1 2 3
for of
特性
- 可遍歷map/objet/array/set/string等
- 避免了
for in
的所有缺點,可以使用break、continue和return,不支援陣列的遍歷,還可以遍歷類似陣列的物件。
例項
for of
是ES6的新語法,為了彌補for in
的侷限性。for of
遍歷的陣列元素值,而且for of
遍歷的只是陣列內的元素,不包括原型屬性和索引
const array = [1, 2, 3];
array.a = 123;
Array.prototype.a = 123;
for(const value of array) {
console.log(value);
}
// 1 2 3
for of
適用遍歷擁有迭代器物件的集合,但是不能遍歷物件,因為沒有迭代器物件,但如果想遍歷物件,可以用內建的Object.keys()
方法
const myObject = {
a: 1,
b: 2,
c: 3
};
for (const key of Object.keys(myObject)) {
console.log(key + ":" + myObject[key]);
}
//> "a:1" "b:2" "c:3
map (陣列方法)
特性
- map不改變原陣列但是會返回新陣列
- 可以使用break中斷迴圈,可以使用return返回到外層函式
例項
const array = [1, 2, 3];
const newArray = array.map(index => {
return index+= 1;
})
console.log(array);// [1, 2 , 3]
console.log(newArray);// [2, 3 , 4]
在大地上我們只過一生。 ----葉賽寧