修改常量

宣告變數 const 只會阻止其值被新值替換const 對物件的內部狀態沒有任何限制。以下示例顯示可以更改 const 物件的屬性值,甚至可以新增新屬性,因為分配給 person 的物件已被修改,但未被替換

const person = { 
    name: "John" 
};
console.log('The name of the person is', person.name);

person.name = "Steve";
console.log('The name of the person is', person.name);

person.surname = "Fox";
console.log('The name of the person is', person.name, 'and the surname is', person.surname);

結果:

The name of the person is John
The name of the person is Steve
The name of the person is Steve and the surname is Fox

在這個例子中,我們建立了一個名為 person 的常量物件,我們重新分配了 person.name 屬性並建立了新的 person.surname 屬性。