var mypafgfr = [];
mypafgfr[0] = "tt";
mypafgfr[1] = "tt";
mypafgfr[2] = "tt";
var outputdata = {};
function ls() {
console.log(mypafgfr[0]); {
var gg = {};
gg["n"] = mypafgfr[0];
gg["image1"] = mypafgfr[1];
gg["image2"] = mypafgfr[2];
outputdata["folder"] = gg;
}
console.log(outputdata);
}
ls();
mypafgfr[0] = "yy";
mypafgfr[1] = "yy";
mypafgfr[2] = "yy";
ls();
在控制台中我期望看到
Object { n="tt", image1="tt", image2="tt"}
Object { n="yy", image1="yy", image2="yy"}
但是我得到了
Object { n="yy", image1="yy", image2="yy"}
Object { n="yy", image1="yy", image2="yy"}
我做错了什么?这是怎么发生的?
最佳答案
那是因为console.<a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/log" rel="noreferrer noopener nofollow">log()</a>
打印对象的引用。
你可以console.<a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/dir" rel="noreferrer noopener nofollow">dir()</a>
而是查看对象在调用时的外观。
您可以使用的另一个后备方法是使用 JSON.<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify" rel="noreferrer noopener nofollow">stringify()</a>
在记录它时,它不指向引用。
console.log(JSON.stringify(outputdata));
关于javascript - 将数据放入对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43082264/