一道面试题-求解

读一下程序,判断输出结果,并分析原因

var apples = ["apple1", "apple2", "apple3"];

for (var i = 0, funs = []; i < 3;i ++){

    funs[i] = function(){

        console.log(apples[i]);

    }

}

funs[0]();

funs[1]();

funs[2]();


隔江千里
浏览 958回答 3
3回答

翻过高山走不出你

闭包解决,经典问闭包的方式,i是全局变量,在调用时其值为3,所以全部是undefined,目前的基本可以采用let来解决了

慕神8447489

闭包是一个自带运行环境的函数,题中的闭包function函数本地作用域中没有i这个变量,只能沿着作用域链往上查找,而上级作用域中的i最终为3。var apples = ["apple1", "apple2", "apple3"];for (var i = 0, funs = []; i < 3;i ++){&nbsp; &nbsp; funs[i] = (function(x){&nbsp; &nbsp; &nbsp; &nbsp; return function(){&nbsp; &nbsp; &nbsp; &nbsp; console.log(apples[x]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })(i);}funs[0]();funs[1]();funs[2]();将代码改成这样的话,就可以分别输出。&nbsp;为什么这样就可以了呢?因为把i每次的值都放到上级作用域链里面了。
打开App,查看更多内容
随时随地看视频慕课网APP