首页 > 解决方案 > 使用保留字 const 定义的变量

问题描述

为什么下面的代码片段会有这样的结果?CONST 类型的变量不能改变它们的值,对吗?

const theDog = {
  name: 'Totó',
  guardian: { name: 'Alan Turing' }
}
const otherDog = { ...theDog, name: 'Tulipa' }
otherDog.guardian.name = 'Maria Luiza'

狗?{ name: 'Totó', guardian: { name: 'Maria Luiza' } }

标签: javascript

解决方案


问题是对象被复制时包含其内部引用,thistheDog.guardianotherDog.guardian引用同一个对象。

解决方案是递归地克隆整个对象:

const theDog = {
 name: 'Totó',
 guardian: { name: 'Alan Turing' }
}
const otherDog = Object.assign({}, theDog, {
    name: 'Tulipa'
});
otherDog.guardian.name = 'Maria Luiza'

const只指定不能改变变量,不能改变引用的对象


推荐阅读