for和可以直接从下标指定的位置开始循环,forEach直接操作不能根据下标选择。
for(let i=0;i<data.length;i++) { //可以修改i值来决定开始循环的位置
console.log(i)
}
data.forEach((item,index)=> {
console.log(item,index) //item代表每一项,index是下标
})
直接操作数组可以选用forEach因为少很多代码量。
for的使用倒循环
for(let i = str.length -1; i >= 0; i--){
console.log(i)
}
场景使用
splice 如果正序循环删除不能删除正确的位
let dataindex = [1,2,3];
let dataList = [2,3,4,5]
for(let i=0;i<dataindex.length;i++) {
dataList.splice(dataIndex[i],1) //每删除一位 整体向前挪一位 不能删除指定元素
}
这个时候就要使用倒叙 从后面删除就会避免这种情况