【发布时间】:2020-12-11 20:35:18
【问题描述】:
我有这部分代码
console.log(b);
let c = b.substr(0);
console.log(b[b.length - 1] + ' ' + c[Math.floor(c.length / 2)]);
c[Math.floor(c.length / 2)] = b[b.length - 1];
console.log(b[b.length - 1] + ' ' + c[Math.floor(c.length / 2)]);
//some code changing c
console.log(c);
似乎 c 和 b 是内存的同一部分,因为 console.log(c); 和 console.log(b); 给出相同的结果,而另外两个 console.logs 给出相同的结果,而第二个显然应该给出两个相同的值(它给出了不同的)。如何正确地复制变量的值,而不会像JSON.parse(JSON.stringify(b)) 这样奇怪?在 JS 中是否有一种既节省时间又节省内存的方法吗?
【问题讨论】: