微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

es6之常/变量

在es5时代声明一个变量或者常量只有var,在es6的时候就出现了变量(let)和常量(const)的具体细分。

1、变量

  用let进行声明变量,更严谨更好使。
  特点:1、不能进行变量提升
       2、不能重复定义同一个变量
       3、不能定义函数的参数。
       4、块级作用域

`//1、不能重复声明同一个变量名
// var num;
// let num = 2; //dentifier 'num' has already been declared
// console.log(num);

//2、不能定义声明函数参数

// function fn1(age) {
//     let age = 12;
//     console.log(age); //Identifier 'age' has already been declared
// }
// fn1(34);

//3、不能进行变量提升
// function fn2() {
//     console.log(num);
//     let num = 13;  //Cannot access 'num' before initialization
// }
// fn2();

//4、块级作用域
for (var index = 0; index < 5; index++) {
    // var num = 25;
    let num = 26;
}
console.log(num); //num is not defined`

2、常量

  用const进行定义,特殊之处就是不可以修改值。
  特点:1、常量声明后需要进行赋值
       2、不能进行修改
       3、不能进行提升
       4、不能重复定义一个常量名
       5、块级作用域

//1、常量声明需要赋值
// const num = 1;
// const num;  //Missing initializer in const declaration
// console.log(num);

// 2、不能重复定义常量
// const num = 1;
// const num = 2;   //Identifier 'num' has already been declared
// console.log(num);

//3、块级作用域

// for (var i = 0; i < 5; i++) {
//     const num = 2;
// }
// console.log(num);  // num is not defined

//4、不能进行提升

// function fn1() {
//     console.log(num);  //Cannot access 'num' before initialization
//     const num = 2;
// }
// fn1();

//5、不能修改    
// const num = 2;
// num = 3;  // Assignment to constant variable.
// console.log(num);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐