let、const、var三种变量声明方式

  参考了网上的一些文章。

  1. let : es6的变量声明方式,具有块级作用域,即所有{}包起来的作用域。不具有变量提升。不能重复定义。存在暂时性死区。
    • 函数
let a = 3
function test(argument) {
    let a = 1;
    console.log(a) // 1
}
test()
    • 循环
for(let j = 1; j < 2; j++) {
    let a = 4;
    console.log(a) // 4
}
console.log(a); // 报错:a is not defined
    • 判断
let a = 1;
if (a) {
    let a = 4;
    console.log(a); // 4
}
console.log(a) // 1
    • 暂时性死区
var a=1if(1){
 console.log(a); // 报错:a is not defined
  let a=2;
}
  1. const: 声明常量,常量不可变,声明时必须赋值,其他特质与let相同
  2. var: 变量提升(只是提升声明,值为undefined),

猜你喜欢

转载自www.cnblogs.com/lurending0417/p/10514832.html