javascript - 记录包含类的数组会打印类的当前版本,而不是记录时的状态
问题描述
我是 JS 新手,来自 iOS 和 Swift 背景。
我声明一个包含一个类的数组,然后更改该类中的一个值。当我在更改值之前和之后打印类时,它似乎打印了类的当前版本。这是一个例子:
class Something {
constructor(name) {
this.name = name
}
}
var somethings = []
somethings.push(new Something("hello"))
console.log(somethings) //object printed with name as "bye"
console.log(somethings[0].name) //"hello"
somethings[0].name = "bye"
console.log(somethings) //object printed with name as "bye"
console.log(somethings[0].name) //"bye"
我在这里误解了什么吗?这是预期的行为吗?
解决方案
这取决于您的浏览器。如果浏览器只保留对您somethings
对象的引用,那么当真实对象更新时,它将在日志中更新。
如果它记录对象的副本,它永远不会改变。
例如看这个片段——当你点击“运行代码片段”时,它会记录一个对象的副本,因此它不会改变:
class Something {
constructor(name) {
this.name = name
}
}
var somethings = []
somethings.push(new Something("hello"))
console.log(somethings) //object printed with name as "bye"
console.log(somethings[0].name) //"hello"
somethings[0].name = "bye"
console.log(somethings) //object printed with name as "bye"
console.log(somethings[0].name) //"bye"
如果您在按“运行代码片段”的同时打开此页面上的浏览器控制台,您将看到,浏览器会按照您的描述准确地记录它。
推荐阅读
- c# - 如何检测方法自上次编译后是否已更改?
- visual-studio - Visual Studio Code 如何更改设置以不恢复旧会话,每次打开新窗口,新会话
- amazon-web-services - Application Load Balancer 的安全组
- mysql - 在mysql的过程中使用'NULL'
- curl - cURL 错误(curl: (18) 传输已关闭,剩余 349 个字节要读取)
- java - 在 Spark 中过滤 KeyValueGrouped 数据集
- python - Pyephem 和 pypredict/gpredict 的区别
- javascript - 为什么 JS Promise 的 async executor 和 async handler 方法表现不同?
- css - 根据祖父类更改伪元素样式
- ios - 没有为团队“XXX”找到具有 AppStore 连接访问权限的帐户