首页 > 解决方案 > 记录包含类的数组会打印类的当前版本,而不是记录时的状态

问题描述

我是 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"

我在这里误解了什么吗?这是预期的行为吗?

标签: javascriptclasslogging

解决方案


这取决于您的浏览器。如果浏览器只保留对您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"

如果您在按“运行代码片段”的同时打开此页面上的浏览器控制台,您将看到,浏览器会按照您的描述准确地记录它。


推荐阅读