search

Home  >  Q&A  >  body text

javascript - Confused about let in for loop in ES6?



As shown in the picture above, it shows that i has been declared, that is, it cannot be declared repeatedly; while in the picture below But it can be re-declared using let, why?

大家讲道理大家讲道理2895 days ago579

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:16:43

    Why can let be repeated? Icon


    Why do let statements conflict with var statements? First, the var statement will be promoted to the top of the current function, that is, the order is as follows:

    1. var i

    2. This is the beginning of the for loop

    3. Just started parsing let i = 0 --->Error report
      Look at the picture again

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-19 10:16:43

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    <code>// for是一个区块,内部又是一个小区块,你的代码可以简写为

    {

        let i = 0;  // i作用于这个大区块

        {

            var i = 'abc'// 此处的i也作用于这个大区块

            console.log(i);

        }

    }

     

    {

        let i = 0; // i作用于这个大区块

        {

            let    i = 'abc'; // i作用于这个小区块

            console.log(i);

        }

    }

     

    // 如果你这么写是可以的

    for (var i = 0; i < 3; i++) {

        let i = 'abc';

        console.log(i);

    }

    // 简写

    {

        var i = 0; // i作用于这个大区块

        {

            let    i = 'abc'; // i作用于这个小区块

            console.log(i);

        }

    }</code>

    reply
    0
  • Cancelreply