遍歷方法

有用到object對象的轉換成數組,而後又想到了遍歷方法,因此,也想記錄下

1. 終止或者跳出循環

  • break跳出循環體,所在循環體已結束
  • continue跳出本次循環,進行下一次循環,所在的循環體未結束
  • return 終止函數執行
for (let i = 0; i < 5; i++) {
    if (i == 3) break;
    console.log("The number is " + i);
    /* 只輸出 0 , 1 , 2 , 到3就跳出循環了 */
}
for (let i = 0; i <= 5; i++) {
    if (i == 3) continue;
    console.log("The number is " + i);
    /* 不輸出3,由於continue跳過了,直接進入下一次循環 */
}

2.遍歷方法

  • 假數據
const temporaryArray = [6,2,3,4,5,1,1,2,3,4,5];
const objectArray = [
    {
        id: 1,
        name: 'd'
    }, {
        id: 2,
        name: 'd'
    }, {
        id: 3,
        name: 'c'
    }, {
        id: 1,
        name: 'a'
    }
];
const temporaryObject = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
};
const length = temporaryArray.length;
  • 普通for循環遍歷
for(let i = 0; i < length; i++) {
    console.log(temporaryArray[i]);
}
  • for in 循環
/* for in 循環主要用於遍歷普通對象,
* 當用它來遍歷數組時候,也能達到一樣的效果,
* 可是這是有風險的,由於 i 輸出爲字符串形式,而不是數組須要的數字下標,
* 這意味着在某些狀況下,會發生字符串運算,致使數據錯誤
* */
for(let i in temporaryObject) {
    /* hasOwnProperty只加載自身屬性 */
    if(temporaryObject.hasOwnProperty(i)) {
        console.log(temporaryObject[i]);
    }
}
  • for of 循環,用於遍歷可迭代的對象
for(let i of temporaryArray) {
    console.log(i);
}
  • forEach 第一個值爲數組當前索引的值,第二個爲索引值,只能遍歷數組,無返回值,也沒法跳出循環
let a = temporaryArray.forEach(function(item, index) {
    console.log(index, item);
});
  • map 返回新數組,只能遍歷數組
temporaryArray.map(function(item) {
    console.log(item);
});
  • filter 是數組的內置對象,不改變原數組,有返回值
temporaryArray.filter(function(item) {
    console.log(item%2 == 0);
});
  • some判斷是否有符合的值
let newArray = temporaryArray.some(function(item) {
    return item > 1;
});
console.log(newArray);
  • every判斷數組裏的值是否所有符合條件
let newArray1 = temporaryArray.every(function(item) {
    return item > 6;
});
console.log(newArray1);
  • reduce(function(accumulator, currentValue, currentIndex, array) {}, initValue)
accumulator:初始值或者累加計算結束後的返回值, currentValue遍歷時的當前元素值,currentIndex當前索引值,array當前數組
initValue爲初始值,若不添加參數initValue,則accumulator爲當前數組的第一個元素值,若添加,則accumulator爲initValue值,累加器accumulator從initValue開始運算
let temporaryObject3 = {};
let newArray2 = objectArray.reduce(function(countArray, currentValue) {
    /* 利用temporaryObject3裏存放id來判斷原數組裏的對象是否相同,若id相同,則繼續下一步,不一樣則將該對象放入新數組中
     * 則countArray爲去重後的數組
      * */
    temporaryObject3[currentValue.id] ? '' : temporaryObject3[currentValue.id] = true && countArray.push(currentValue);
    return countArray;
}, []);
console.log(newArray2);
正在努力學習中,若對你的學習有幫助,留下你的印記唄(點個贊咯^_^)
相關文章
相關標籤/搜索