<span style="font-size: 15px"><code>我在整理闭包问题的时候,看到一道前端面试题<br/>for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 0);
}<br/>了解 js 的异步机制的都知道,输出结果是: <code>10 10 10 ... 10<br/></code>然后面试官又问 如果希望得到的是<code>0 1 2 ... 9</code>,如何能够解决这个问题<br/><br/>我脑海想到的第一个解决方法就是用let代替var使for形成块级作用域;<br/><br/>第二个解决方法,使setTimeout函数立即执行,形成同步输出:<br/></code></span><span style="font-size: 15px"><code>for (var i=0; i < 10; i++) {
(function (temp) {
setTimeout(function() {
console.log(temp);
}, 0);
})(i);
}<br/><br/>如果有其他解决方法,亲爱的朋友们可以评论补充<br/><br/>再补充一道闭包问题:<br/></code></span>function fun(n,o){
console.log(o);
return {
fun:function(m){
return fun(m,n);
}
}
}
var a=fun(0);
a.fun(1);
a.fun(2);
a.fun(3);
var b=fun(0).fun(1).fun(2).fun(3);
var c=fun(0).fun(1);
c.fun(2);
c.fun(3);<span style="font-size: 15px"><code>这道题可以较深理解闭包机制,解决这道题比较重要的是理解被保护的数据是哪一个,运行的顺序之类的,输出:<br/></code></span>
var a=_fun_(0);//undefined a.fun(1);//0 a.fun(2);//0 a.fun(3);//0 var b=_fun_(0).fun(1).fun(2).fun(3); //undefined,0,1,2 var c=fun(0).fun(1);//undefined,0, c.fun(2);//1 c.fun(3); //1
<span style="font-size: 15px"><code>我在这就不多做解释了,想一下很容易通的<br/><br/><br/></code></span>
<br/>
以上就是关于闭包问题的详细介绍(二)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号