javascript - 关于nzakas对const和let解释的一点疑问

 手机用户2502876273 发布于 2022-11-14 06:52

先附上nzakas的讲解地址:
https://github.com/nzakas/understandinges6/blob/master/manuscript/01-Block-Bindings.md
在zakas对let的讲解中举的例子:

var funcs = [];
for (let i = 0; i < 10; i++) {
    funcs.push(function() {
        console.log(i);
    });
}

funcs.forEach(function(func) {
    func();     // outputs 0, then 1, then 2, up to 9
})

其解释为
1.On each iteration, the loop creates a new variable and initializes it to the value of the variable with the same name from the previous iteration.

2.The let declaration creates a new variable i each time through the loop, so each function created inside the loop gets its own copy of i. Each copy of i has the value it was assigned at the beginning of the loop iteration in which it was created

这意味着每次迭代,都会重新用let声明i,赋值,并且产生一个新的块级域,我这样理解对不对呢?是否等价于{let i = 0;...}{let i = 1;...}...{let i = 9;...}分为10个块级域,而且每个i都处在不同块级域之中呢?
但是同为块级域的const:
var funcs = [];
// throws an error after one iteration
for (const i = 0; i < 10; i++) {
funcs.push(function() {
    console.log(i);
});
}
为什么不会在每次迭代中重新声明赋值并且产生新的块级域呢?像{const i = 0;...}{const i = 1;...}...{const i = 9;...}这样呢?这是否说明const和let在for迭代中的行为不同呢?
然而,在for-in和for-of循环之中,为什么let与const又是相同的?
var funcs = [],
object = {
    a: true,
    b: true,
    c: true
};

// doesn't cause an error
for (const key in object) {
funcs.push(function() {
    console.log(key);
});
}

funcs.forEach(function(func) {
func();     // outputs "a", then "b", then "c"
});
其解释为The for-in and for-of loops work with const because the loop initializer creates a new binding on each iteration through the loop rather than attempting to modify the value of an existing binding
这里有一些不解,每次产生新绑定和在现有绑定上修改之间有什么区别吗?for-in循环不是将属性名赋值给变量吗?为什么是产生绑定了?每迭代一次key的值不都变了吗?为什么仍然能够工作呢?
刚学ES6,对以上实在有些不解,还望大神解答!


2 个回答
  • for 10 次等于把 i 重新赋值 10 次,const 不允许重新赋值

    for..in/of 每次都是声明新变量,不存在重复赋值,所以 const 无碍

    2022-11-14 07:10 回答
  • 求解呀,求解呀

    2022-11-14 07:10 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有