let与var区别

<!DOCTYPE html>
<html>
<head>
    <title>let与var区别</title>
    <meta charset="UTF-8">
    <script type="text/javascript">
        console.log("var");
        
        var a = [];
        for (var i = 0; i < 10; i++) {
            a[i] = function () {
                console.log(i);
            };
        }
        a[6](); // 输出10

      
        
        console.log("let");
        var a = [];
        for (let i = 0; i < 10; i++) {
            a[i] = function () {
                console.log(i);
            };
        }
        a[6](); // 输出6
        
    </script>
</head>
<body>

</body>
</html>

1、let不允许在相同作用域内,重复声明同一个变量

2、let声明的变量只在它所在的代码块有效

猜你喜欢

转载自www.cnblogs.com/legendheng/p/10265674.html
今日推荐