JavaScript学习笔记_ES6_常量和局部变量
2019-11-19 本文已影响0人
菜出意料
JavaScript中的常量和局部变量是在Mozilla项目中首先被提出并实现,随后被纳入ES6标准。
常量——关键字const
常量可以理解为不可重复复置的变量,对常量重新赋值会报错,同一作用域下对常量的重复声明会报错。
// 同一作用域重复声明同名变量
var a = 1
const a = 3 // SyntaxError: Identifier 'a' has already been declared
// 赋值报错
const a = 3
a = 2 // TypeError: Assignment to constant variable.
下面的例子可以说明常量具有块级作用域。
// 不同作用域下重复声明
const a = 2
// 下面是块级作用域
{
const a = 3
console.log(a) // 3
}
console.log(a) //2
常量在声明时必须初始化。
// 常量在声明时必须初始化,否则报错
const a // SyntaxError: Missing initializer in const declaration
在作用域外使用常量会报错。
{
const b = 4
}
console.log(b) // ReferenceError: b is not defined
常量不会像var关键字声明的变量一样(变量)提升。变量提升知识点传送门。常量只能在初始化后使用。
function f () {
console.log(b) // ReferenceError: Cannot access 'b' before initialization
const b = 2
}
f()
常量是对象或数组时,无法给它重新赋值(即不能使用'常量名'=其他值),但可以操作其引用数据。
const o = {}
o.x = 1
console.log(o) // { x: 1 }
o = {} // TypeError: Assignment to constant variable.
const arr = []
arr.push(1, 2, 3) // arr => [1, 2, 3]
arr.pop() // arr => [1, 2]
arr = [4] // TypeError: Assignment to constant variable.
局部变量——关键字let
在同一作用域下,不能重复声明局部变量。
let a
let a = 1
// SyntaxError: Identifier 'a' has already been declared
具有块级作用域,在作用域外访问局部变量会报错。
{
let a = 1
}
console.log(a) // ReferenceError: a is not defined
局部变量在循环中使用闭包时非常有用。
let arr = []
for (let i = 0; i < 10; i++) {
arr[i] = function () {
console.log(i)
}
}
arr[7]() // 7
不存在变量提升,局部变量必须声明后使用。
console.log(a) // ReferenceError: Cannot access 'a' before initialization
let a = 1
最后:在使用常量时,一定要先初始化再使用;使用局部变量时,一定要先声明再使用。常量和局部变量禁止未定义就使用!!!