猿问

结果为什么是不是4呢?


function makeClosures(arr, fn) {

    var result = new Array();

     for(var i=0;i<arr.length;i++){

        result[i] = function(){

            return fn(arr[i]);

        };

    }

    return result;

}


console.log(makeClosures([1, 2, 3], function (x) {

    return x * x;

}));


繁星coding
浏览 621回答 2
2回答

慕妹3146593

&nbsp; &nbsp; function makeClosures(arr, fn) {&nbsp; &nbsp; &nbsp; let result = new Array();&nbsp; &nbsp; &nbsp; // 如果用var,注意闭包问题&nbsp; &nbsp; &nbsp; for (let i = 0, len = arr.length; i < len; i++) {&nbsp; &nbsp; &nbsp; &nbsp; result[i] = function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return fn(arr[i]);&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; }&nbsp; &nbsp; let testArr = [1, 2, 3]&nbsp; &nbsp; let fn = function (x) {&nbsp; &nbsp; &nbsp; return x * x;&nbsp; &nbsp; }&nbsp; &nbsp; // 条件一, 返回一个函数数组,长度和arr相同&nbsp; &nbsp; let result = makeClosures([1, 2, 3], fn);&nbsp; &nbsp; // 条件二, result[i]() 和 fn(arr[i]) 结果相同&nbsp; &nbsp; console.log('测试 i = 0', 'result[i]: ', result[0](), ' fn(arr[i]): ', fn(testArr[0])) // 1&nbsp; &nbsp; console.log('测试 i = 1', 'result[i]: ', result[1](), ' fn(arr[i]): ', fn(testArr[1])) // 4&nbsp; &nbsp; console.log('测试 i = 2', 'result[i]: ', result[2](), ' fn(arr[i]): ', fn(testArr[2])) // 9

杨__羊羊

你这题目是不是有问题搜了一下 输出是个函数 result[1]()的结果是4输入例子:[1, 2, 3], function (x) {&nbsp;return x * x;&nbsp;}输出例子:result[1]()4
随时随地看视频慕课网APP
我要回答