1.在固定长度或者长度不需要计算的时候for循环效率高于foreach,foreach在循环次数未知或者计算起来较复杂有损性能的情况下效率比for循环高。
2.foreach适用于只是进行集合或数组遍历,for则在较复杂的循环中效率更高。什么是复杂环境呢?就是要对原数组进行修改时。
3.foreach与for循环的明显差别在于foreach循环时循环对象(数组、集合)被锁定,不能对循环对象中的内容进行增删改操作,不能通过下标访问循环对象各项的值。
4.forEach相比普通的for循环的优势在于对稀疏数组的处理,会跳过数组中的空位。
let array=[1,,3,,5,,,8]
array.forEach((ele,index,arr)=> {
console.log(ele,index,arr)
//index: 0 2 4 7
//ele: 1 3 5 8
});
console.log("------------------------")
for(let i=0;i<array.length;i++){
console.log(i,array[i])
//i:0 1 2 3 4 5 6 7
//array[i]: 1 undefined 3 undefined 5 undefined undefined 8
}