const 的值不能通过重新赋值来改变,也不能重新声明。
const testData = { name:"Sandeep",lastName:"Mukherjee",company:"XYZ"}
第一个案例
testData = {name:"hello"}
console.log(testData);//throws an Error:Assignment to constant variable
Here we are reassigning testData again
第二种情况
const testData = {name:"Sandeep",lastName:"Mukherjee",company:"ABC"}
console.log(testData); //throws an Error: Identifier 'testData' has already been declared
Here we are redeclaring testData again
当使用 const 声明变量时,这意味着它指向某个内存位置 const 的行为是我们可以操作存储在该内存位置但不能操作内存位置的值,当我们重新分配/重新声明它不允许更改的 const 变量时内存位置
我们可以改变特定键的值
testData.company = "Google"
console.log(testData);
//{ name: 'Sandeep', lastName: 'Mukherjee', company: 'Google' }
我们可以向它添加任何新的键值对
testData.homeTown = "NewYork"
console.log(testData)
//{name: 'Sandeep',lastName:'Mukherjee',company:'Google',homeTown: 'NewYork'}