ES6-const

作者: 东邪_黄药师 | 来源:发表于2018-10-31 14:12 被阅读24次

    const也用来声明变量,但是声明的是常量。
    一旦声明,常量的值就不能改变
    例子:

    const Pi = 3.1415926535;
    console.log(Pi);
    Pi = 3; // Pi is read-only -- Error
    console.log(Pi);
    

    const块级作用域:

      if (true) {
        const Pi = 3.14159265;
    };
    console.log(Pi);    //Pi is not defined
    

    const暂时性死区:

     if (true) {
        console.log(Pi);    //undefined
        const Pi = 3.14159265;
    };
    

    不可重复声明:

    {
        var a   = 100;
        const a = 200;
        console.log(a);
    }
    

    const对象:

    const person = {};
    person.name  = "Zhangsan";
    person.age   = 30;
    
    console.log(person.name);   //Zhangsan
    console.log(person.age);    //30
    console.log(person);        //Object {name: "Zhangsan", age: 30}
    
    
         //如果再次输出person={}结局如下:;
           person = {}; //person is read-only
    

    ==========================================================

     const arr = [];
    console.log(arr);
    console.log(arr.length);
    console.log("------");
    arr.push("Hello world!");
    console.log(arr);
    console.log(arr.length);
    console.log("------");
    arr.length = 0;
    console.log(arr);
    console.log(arr.length);
    console.log("------");
    
    // 再次arr会报错
    arr = ["Hello Everyone!"];
    

    相关文章

      网友评论

          本文标题:ES6-const

          本文链接:https://www.haomeiwen.com/subject/usnotqtx.html