對空位的處理
for循環(不會忽略空位,標記undefined)
var arr =[1,2,undefined,3,null,,7]
for (let i=0;i<arr.length;i++) {
console.log('for循環',arr[i])
}
結果:
for循環 1
for循環 2
for循環 undefined
for循環 3
for循環 null
for循環 undefined
for循環 7
for of(不會忽略空位,標記undefined)
for(let i of arr) {
console.log('for of',i)
}
結果:
for of 1
for of 2
for of undefined
for of 3
for of null
for of undefined
for of 7
for in(會忽略空位)
for(let i in arr) {
console.log('for in',arr[i])
}
結果:
for in 1
for in 2
for in undefined
for in 3
for in null
for in 7
forEach(會忽略空位)
arr.forEach(item => console.log('foreach',item))
結果:
foreach 1
foreach 2
foreach undefined
foreach 3
foreach null
foreach 7
map(會忽略空位),filter,every,some,find,findIndex都會忽略空位
arr.map(item => console.log('map',item))
結果:
map 1
map 2
map undefined
map 3
map null
map 7
性能對比
var arr =new Array(100000).fill(1)
console.time('for循環')
for (let i=0;i<arr.length;i++) {
}
console.timeEnd('for循環')
console.time('緩存優化的for循環')
for (let i=0,len=arr.length;i<len;i++) {
}
console.timeEnd('緩存優化的for循環')
console.time('foreach循環')
arr.forEach(item => {} )
console.timeEnd('foreach循環')
console.time('for of 循環')
for(let i of arr) {
}
console.timeEnd('for of 循環')
console.time('for in 循環')
for(let i in arr) {
}
console.timeEnd('for in 循環')
console.time('map循環')
arr.map(item => {})
console.timeEnd('map循環')
結果:
for循環: 3.226ms
緩存優化的for循環: 1.965ms
foreach循環: 2.144ms
for of 循環: 5.128ms
for in 循環: 11.501ms(最好不要用,可能會遍歷原型鏈上的屬性)
map循環: 13.134ms
注意lz在對數組的循環中沒有做任何處理僅僅是空代碼來比較性能,map循環直接返回空數組,在對數組進行淺拷貝上占用內存低,for of循環也對占用內存上進行了一定的優化,而for與for of可以隨時中斷循環與跳出循環。拋開業務場景和使用便利性,單純談性能和效率是沒有意義的
ES6新增的諸多數組的方法確實極大的方便了前端開發,使得以往復雜或者冗長的代碼,可以變得易讀而且精煉,而好的for循環寫法,在大數據量的情況下,確實也有着更好的兼容和多環境運行表現