复制变量node.js

问题描述

我有这部分代码

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中是否有一种节省时间和内存的有效方法

解决方法

substr函数返回一个新的String(新对象),因此c和b是不同的对象。

此外,通过为某个索引分配不同的字符来更改String也不起作用,因为它不会更改原始对象。

如果您要执行的操作是替换特定索引处的字符,请参阅以下有用的文章: How do I replace a character at a particular index in JavaScript?