【问题标题】:copying variables node.js复制变量 node.js
【发布时间】: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 中是否有一种既节省时间又节省内存的方法吗?

【问题讨论】:

    标签: node.js variables let


    【解决方案1】:

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

    此外,通过为某个索引分配不同的字符来更改字符串是行不通的,因为它不会更改原始对象。

    如果您想要替换特定索引处的字符,这里有一篇有用的帖子: How do I replace a character at a particular index in JavaScript?

    【讨论】:

    • 啊啊啊。我无法更改 JS 中的字符串。不知道,非常感谢
    • 当然,没问题:)
    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 2017-09-04
    • 2013-06-04
    • 2018-11-17
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 2016-03-26
    相关资源
    最近更新 更多