arr1是直接定义的Json对象数组,赋值正常,arr2是循环添加的Json对象数组,赋值异常,下面是输出结果和源代码
const app = getApp() Page({ data: { a: '1' }, onLoad: function () { this .bugtest() }, bugtest: function () { console.log( '开始' ) let i let arr1 = [] let arr2 = [{ "code" : "1" , "text" : "1" , "t" : "1" , "ms" : "1" }, { "code" : "1" , "text" : "1" , "t" : "1" , "ms" : "1" }, { "code" : "1" , "text" : "1" , "t" : "1" , "ms" : "1" }] let m = { "code" : "1" , "text" : "1" , "t" : "1" , "ms" : "1" } for (i = 0; i < 3; i++) { arr2[i].code=i+1 } console.log(arr2) for (i = 0; i < 3; i++) { arr1.push(m) } console.log(arr1) arr1[0].code=5 } }) |
你的预期是?
请使用代码片段复现情况
https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html
for
(i = 0; i < 3; i++) {
arr1.push(m)
}
改为
for
(i = 0; i < 3; i++) {
arr1.push(JSON.parse(JSON.stringify(m)))
}
就行了 请了解一下数据的拷贝