工作發現,項目中的對於對象、數組的循環,使用的方法各不相同,有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]
在大地上我們只過一生。 ----葉賽寧