javascript - 使用保留字 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' } }
解决方案
问题是对象被复制时包含其内部引用,thistheDog.guardian
和otherDog.guardian
引用同一个对象。
解决方案是递归地克隆整个对象:
const theDog = {
name: 'Totó',
guardian: { name: 'Alan Turing' }
}
const otherDog = Object.assign({}, theDog, {
name: 'Tulipa'
});
otherDog.guardian.name = 'Maria Luiza'
也
const
只指定不能改变变量,不能改变引用的对象
推荐阅读
- c++ - How to return QVariant type array
- javascript - 如何在 JavaScript 中的 forEach 循环的每一行上做一个数学函数?
- python-3.x - 从未使用过如此混乱的数据结构
- javascript - 尝试使用 IF 语句自动填充单元格
- react-native - ASP.NET WebAPI - 使用 FormData 上传文件没有所有表单数据字段
- android - 单击 VCS > Shelve Changes 后,我的 Android Studio 项目文件全部删除,我可以恢复它们吗?
- f# - 需要取每个月最早的日期
- html - Amplitude.js - 直播
- vba - 如何将 excel VBA UI 放在前面
- ios - 无法构建模块基础