代码之家  ›  专栏  ›  技术社区  ›  leonardofed

双让声明:如何让提升工作在环?

  •  3
  • leonardofed  · 技术社区  · 7 年前

        function foo(n){
            for (let i = 0; i < n; i++) {       
                console.log(i);
                let i = 10;
            }
        }
    
        foo(4);
    
    // OUTPUT: ReferenceError: i is not defined
    

    let i 声明两次。首先,在初始化过程中关闭,然后在for循环本身中关闭。

    i is not defined 而不是 Identifier 'i' has already been declared

    3 回复  |  直到 6 年前
        1
  •  2
  •   lonesomeday    7 年前

    let 变量应该像所有其他类型的声明一样被提升。

    提升,不像 var const 变量是相同的。

    在到达声明之前,不能访问相关范围中的变量。这有点无济于事,被称为 Useful 2ality blog

    function foo(n){
        for (let i = 0; i < n; i++) {       
            // i cannot be accessed
            let i = 10;
            // i is set to 10
        }
    }
    
    foo(4);
    

    for 对于 {}

        2
  •  1
  •   leonardofed    7 年前

    下面发生的是,javascript在同一for循环中看到两个不同级别的块作用域。

    • let inside the for loop: i is set to undefined
    • 由于每次提升, let and const are declared but not initialized(as undefined )it throws a referenceerror.

      let i = 0; )循环内部的第二个。

      • let i = 0 (二)
      • for循环: i is set to undefined

      enter image description here

      console.log(i) let i 让我

      const 声明但未初始化(作为 undefined

        3
  •  -2
  •   Itamar    7 年前

    接入MDN:

    function test(){
      var foo = 33;
      if (true) {
       let foo = (foo + 55); // ReferenceError
      }
    }
    test();
    

    在这一行中,if块的“foo”已经在词汇环境中创建,但尚未达到(并终止)其初始化(这是语句本身的一部分):它仍处于时间死区。

    MDN参考号: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let 暂时死区