淺談js中的遍歷

遍歷是程序中必不可少的一環,在全部語言中都存在,由於它能夠簡化人們的規律性操做,本文將一一道來。es6

for++

這是最基礎的for循環語句,格式以下:數組

var arr = [1, 2, 3, 4, 5]
    for (var i = 0; i < arr.length; i++) {
        console.log(i)
        if (i > 2) break
    }

也有人這樣寫,聽說效率更高es5

for (var i = 0, len = arr.length; i < len; i++) {
        console.log(i)
        if (i > 2) break
    }

while

for循環能夠同時拿到每一個循環的索引和數組對應的項,若是隻是知足必定條件內的循環,可使用while code

var i = 0
    while (i < 5) {
        console.log(i)
        if(i>2)break
        i++
    }

forEach, map, filter

上述方法寫起來略微麻煩,因此es5新增了幾個對數組的遍歷方法,此外還有every,some,reduce,不過不是很經常使用。這幾個方法會完整地遍歷數組,即便在知足條件return後,循環依舊進行。
用法以下:對象

// forEach 直接遍歷
arr.forEach((item, index) => {
        console.log(item, index)
    })
    
// map 依次遍歷,對每一項進行轉換,映射成另外一個數組
const arr1 = arr.map((item, index) => {
        return item * 2
    })
console.log(arr1) // [2,4,6,8,10]

// filter 依次遍歷,過濾獲得知足條件的項,組成數組
const arr2 = arr.filter((item, index) => {
        return item % 2 == 0
    })
console.log(arr2) // [2,4]

for...of

這個是es6推薦的數組遍歷方法,相比forEach,優勢有2點:
1.可使用break和continue跳出循環
2.找到知足條件的項,跳出循環後,後面的循環不會進行,從而減小內存消耗。索引

for (const item of arr) {
        console.log(item)
        if (item > 2) break
    }
    
// 若是要同時遍歷索引和項
for (const [index, item] of arr.entries()) {
        if (index === 2) {
            console.log(item)
            break
        }
    }

for...in

上述都是遍歷數組的方法,這個是遍歷對象的方法,而且最好不要混用內存

const obj = {
        a: 1,
        b: 2,
        c: 3
    }
for (const key in obj) {
    console.log(key, obj[key])
}
相關文章
相關標籤/搜索