gpt4 book ai didi

javascript - Javascript 中的引用数据类型和原始数据类型

转载 作者:行者123 更新时间:2023-11-30 11:53:14 24 4
gpt4 key购买 nike

在以下两个片段中:

​var person = "Kobe";  
​var anotherPerson = person; // anotherPerson = the value of person​
person = "Bryant"; // value of person changed​

console.log(anotherPerson); // Kobe​
console.log(person); // Bryant

如果我们使用 Object :

var person = {name: "Kobe"};
​var anotherPerson = person;
person.name = "Bryant";

console.log(anotherPerson.name); // Bryant​
console.log(person.name); // Bryant

第一个记录变量 anotherPerson 的“Kobe”,但如果 anotherPerson 引用了变量 person,则 person 发生的任何变化也应该反射(reflect)另一个人,对吗?

谁能详细解释一下

谢谢

最佳答案

在您的第一个示例中,您有 2 个变量引用 "Kobe"。虽然通过将 "Bryant" 分配给 person 变量,您正在更改该变量的引用。所以最后你得到了 2 个变量,每个变量都引用另一个字符串。由于 JS 中的原始类型是不可变的,因此无法“更改字符串的值”。您只能分配一个新字符串。

enter image description here

在您的第二个示例中,您只是更改了所引用对象的属性,尽管引用当然保持不变。

enter image description here

关于javascript - Javascript 中的引用数据类型和原始数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38844450/

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