js const声明基本数据类型与引用数据类型需要注意

const 实际上是保证其声明的变量在栈中的值不可改变

  • 对于基本数据类型,栈中直接保存变量的值,值不可改变,等同于常量
  • 对于引用数据类型,栈中保存的是变量的地址,地址不可改变,地址为常量;但地址指向的堆中的值可以变
// 基本数据类型
const str = 'hello';
str = 'hello world';		// VM297:1 Uncaught TypeError: Assignment to constant variable.

// 引用数据类型
const o = {
    
    
	'str': 'hello'
}
o = {
    
    'str': 'hello world'}	// VM297:1 Uncaught TypeError: Assignment to constant variable.
o['str'] = 'hello world';	// {'str': 'hello world'}

猜你喜欢

转载自blog.csdn.net/SJ1551/article/details/107768528