Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

js let一个问题

for(let i=0;i<el.length;++i)
{
    el[i].addEventListener(click,function()
    {
        console.log(i);
    });
}

一个问题为什么let可以无视i最后的值?而可以根据最初的i进行打印


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

是因为 ES6 新增了块作用域的存在。

对于 let 来说,每次 for 循环内部都是一个新的块,下一次循环块里访问的是 i 就是自己这个块里的,跟上一次循环没关系。

用 ES6 之前的函数作用域来模拟块作用域的话,就类似于:

var i;
for(i = 0; i < el.length; ++i) {
    function func(tmp) {
        el[tmp].addEventListener('click', function() {
            console.log(tmp);
        });
    }
    
    func(i);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...