ECMAScript 6 defines variable keywords var, let, const

define variables

ES6 has added two new keywords let and const that can define variables, plus the previous var, let's take a look at the differences and usage scenarios of these three:

 var a   = 1 
 let b   = 2
 const c = 3
 console.log(a,b,c)

//在一个作用域内已经声明的变量,不允许再次定义。 
 var a = 1        //允许重新定义
 // let b = 2    //错误,无法重新定义
 // const c=3    //错误,无法重新定义
 
 // let 可以重新赋值 ,const 不允许重新赋值
 b = 22          //可以 
 c = 2           //不可以 

constant immutable

The variable defined by const is immutable, which means that the memory address corresponding to the constant must not be changed, rather than the corresponding value must not be changed, that is, the composite data type value is variable

const aa=1 //值不可变
const bb="string" //值不可变
const cc =true //值不可变

const dd ={
    
    a:1,b:2} //可变
dd.a = 2
console.log(dd); //{a:2,b:2}

//那如果要创建一个不可变的对象呢?
//使用Object.freeze()
//例子1:
const ee = Object.freeze({
    
    a:1,b:2})
ee.a=2 //无效,但不会报错,可以使用严格模式,就会报错 "use strict"
console.log(ee)

//例子2:
const ff = Object.freeze(["星期一","星期二"])
ff[0]="测试修改" //无效,但不会报错,可以使用严格模式,就会报错 "use strict"
console.log(ff)

scope

In ECMA 6, there are three scopes, global scope, function scope, block-level scope, var will not generate block-level scope, let and const will generate block-level scope

//var 
for(var i=1;i<10;i++){
    
    

}
console.log(i)

//let
for(let j=1;j<10;j++){
    
    
	console.log(j)
}
// console.log(j); //变量未定义,因为for{}形成了一个快级作用域,无法访问到

if(true){
    
    
	const k=23
}
// console.log(k) //变量未定义,因为if{}形成了一个快级作用域,无法访问到

Summarize

var is not used, generally const is used, if the value is determined to be modified, let is used to define

おすすめ

転載: blog.csdn.net/mrtwenty/article/details/123393750