gpt4 book ai didi

javascript - 为什么这会发生在 javascript 中?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:57:43 24 4
gpt4 key购买 nike

今天我在 javascript 中遇到了这个问题,但不知道为什么会这样。

var a = {
prop: {
bool: true
}
};

console.log(a.prop.bool); // logs true
var b = a;
b.prop.bool = false;
console.log(a.prop.bool); // logs false ¿?

最佳答案

表达式 { prop: ... } 表达式被计算一次以创建一个对象。

ab 都是对该单个对象的引用

参见 What's the difference between passing by reference vs. passing by value?http://en.wikipedia.org/wiki/Reference_(computer_science)

References are widely used in programming, especially to efficiently pass large or mutable data as arguments to procedures, or to share such data among various uses.

编辑

clone from underscore 进行浅拷贝。

Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.

要创建深拷贝,最简单的方法可能是序列化和反序列化。如果 a 有引用循环,这会做一些奇怪的事情。

var b = JSON.parse(JSON.stringify(a));

关于javascript - 为什么这会发生在 javascript 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7681615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com