1.不改变原数组
let obj = {'1':1}
let oldArr = ['1',1,obj,true]
oldArr.forEach((el)=>{
el = 1
})
console.log(oldArr)
[
"1",
1,
{
"1": 1
},
true
]
2.改变原数组
let obj = {'1':1}
let oldArr = ['1',1,obj,true]
oldArr.forEach((el)=>{
if(typeof el == 'object'){
el['2']=2
}
el = 2
})
console.log(oldArr)
[
"1",
1,
{
"1": 1,
"2": 2
},
true
]
3.结论:forEach方法不能改变数组里的基本变量
let a = 1
let obj = {'1':1}
let oldArr = ['1',1,obj,true,a]
oldArr.forEach((el,index)=>{
// if(typeof el == 'object'){
// el['2']=2
// }
oldArr[index] =2
})
console.log(oldArr)
forEach方法里操作对象生效,想要操作里面的基本数据类型,就用arr[i]的形式直接操作数组。
转载于 https://blog.csdn.net/ZhengKehang/article/details/81281563