es6 let和const

一、let

1、let块作用域

if(true){
            var a=1;
            let b=2;
        }
        console.log("a:"+a);//a:1
        console.log("b:"+b);//Uncaught ReferenceError: b is not defined

2、let常用于for循环

  var a=[];
    for (let i = 0; i < 10; i++) {
        a[i] = function () {
            console.log(i);   //6 //变量i是let声明的,当前的i只在本轮循环有效。所以每一次循环的i其实都是一个新的变量,于是最后输出的是6
        };
    }
    a[6]();

3、typeof不再是一个百分之百安全的操作

   console.log(typeof x);//undefined
   console.log(typeof y);//Uncaught ReferenceError: y is not defined
    var x=2;
    let y=3;

typeof运行时y尚未声明,所以报错。

4、隐蔽的暂时性死区

    //正确
    function bar(x=2, y=x) {
        return [x, y];
    }
    console.log(bar());//[2,2]
//报错
 function bar(x=y, y=2) {
        return [x, y];
    }
    console.log(bar());//Uncaught ReferenceError: y is not defined

5、不允许重复声明

不能在函数内重复声明参数

function bar(arg) {
        let arg;//Uncaught SyntaxError: Identifier 'arg' has already been declared
    }

二、const

1、const声明的变量也是块作用域,但是不能被多次修改

let a=10;
        const b=20;
        console.log(a);
        console.log(b);
        a=100;
        b=200;//Uncaught TypeError: Assignment to constant variable.

2、const 声明变量时必须赋值

const a;//Uncaught SyntaxError: Missing initializer in const declaration

3、const可以指定为对象

const常亮指向对象的指针不能变,对象本身是可以改变的

let user={name:"starof",age:25};
        const LOVE_YOU=user;
        console.log(user);
        /*LOVE_YOU=1;//报错*/
        user.age=18;
        console.log(user);

三、babel【update20170605】

下面代码在es5中输出inside,在es6中输出outside。

如果确定是在es5中还是在es6中运行?可以通过babel使其在es6中执行。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="js/browser.js"></script>
</head>
<body>
<script type="text/babel">
    function f() {
        console.log("outside");
    }
    (function () {
        if (true) {
            //重复 声明f
            function f() {
                console.log("inside"); //babel解析为es6所以输出outside
            }
        }
        f();
    }())
</script>

 四、全局变量和全局对象的属性【update20170605】

es6中规定:

var和function声明的全局变量,依旧是全局对象的属性

let,const声明的全局变量不属于全局对象的属性

以下代码输出什么结果?

let b=1;
console.log(window.b++);//NaN

本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/6919624.html有问题欢迎与我讨论,共同进步。

原文地址:https://www.cnblogs.com/starof/p/6919624.html