五种方法分别为(按顺序):
for(let i=0;i<arr.length;i++)
for(let i in arr)
for(let i of arr)
arr.forEach
arr.map
测试对象:一个长度为1000000(一百万)的数组,数组每一项都是 1
let arr = new Array(1000000).fill(1)
console.log(arr);
console.time('t1')
let count1 = 0
for(let i=0;i<arr.length;i++){
count1++
}
console.timeEnd('t1')
console.time('t2')
let count2 = 0
for(let i in arr){
count2++
}
console.timeEnd('t2')
console.time('t3')
let count3 = 0
for(let i of arr){
count3++
}
console.timeEnd('t3')
console.time('t4')
let count4 = 0
arr.forEach(i=>{
count4++
})
console.timeEnd('t4')
console.time('t5')
let count5 = 0
arr.map(i=>{
count5++
})
console.timeEnd('t5')
三次测试结果
t1: 3.037ms for(let i=0;i<arr.length;i++)
t2: 145.701ms for(let i in arr)
t3: 60.051ms for(let i of arr)
t4: 11.56ms arr.forEach
t5: 15.574ms arr.map
t1: 2.619ms
t2: 139.822ms
t3: 60.563ms
t4: 11.192ms
t5: 15.275ms
t1: 2.447ms
t2: 134.357ms
t3: 58.68ms
t4: 11.597ms
t5: 15.715ms