Const
need to be const
but I need to change the value died
.
const person = {
name: 'Bowie',
died: 2012
}
person = {
name: 'Bowie',
died: 2016
}
console.log(person);
答案 0 :(得分:1)
Whilst you cannot replace the value of a const
variable, if its value is an object you can still by default change the properties within that object.
const person = {
name: 'Bowie',
died: 2012
}
person.died = 2016;
console.log(person);
The exceptions are if the whole Object has been "frozen", or if the specific property has been set as unwritable.
答案 1 :(得分:1)
Try this one:
Here you can not assign a new object to person
as it is a const
but you can edit the existing object.
The 'person' variable here holds the reference to the object and if you change the contents of the object then you are not changing the reference.
Hence no error with const
like this.
person.died = 2016
答案 2 :(得分:0)
change it like the following
person['died'] = 1976
答案 3 :(得分:0)
The const
declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its parameters) can be altered .
Try this code:
const person = {
name: 'Bowie',
died: 2012
}
person.died= 2016;
console.log(person);