猿问

关于一段JS代码的问题

function createFunction() {

    var result = new Array();

    for (var i = 0; i < 10; i++) {

        result[i] = function() {

            return i;

        };

    }

    return result;

}


console.log(createFunction());

如题上一段代码为什么输出的是

[ [Function],

[Function],

[Function],

[Function],

[Function],

[Function],

[Function],

[Function],

[Function],

[Function] ]


慕丝7291255
浏览 570回答 3
3回答

Smart猫小萌

createFunction()返回一个数组,数组的元素都是匿名函数function

慕田峪7331174

没毛病result就是这样的[function()&nbsp;{return&nbsp;i;},&nbsp;function()&nbsp;{return&nbsp;i;},&nbsp;function()&nbsp;{return&nbsp;i;}]

FFIVE

看一个函数,首先关注的是函数的参数和返回值。createFunction()这个函数没有参数,return的是一个数组。result[0] = function(){}result[1] = function(){}result[2] = function(){}...result[9] = function(){}所以显示result这个数字的每一项,都是一个匿名函数,里面的匿名函数return i如果你去尝试调用里面的任意一个匿名函数,你会痛苦的发现,return回来的结果都是10...改成这样,就是你想要的function createFunction() {&nbsp; &nbsp; var result = new Array();&nbsp; &nbsp; for (var i = 0; i < 10; i++) {&nbsp; &nbsp; &nbsp; &nbsp; result[i] = (function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i;&nbsp; &nbsp; &nbsp; &nbsp; })(i)&nbsp; &nbsp; }&nbsp; &nbsp; return result;}var arr = createFunction();console.log(arr);或者用ES6的letfunction createFunction() {&nbsp; &nbsp; var result = new Array();&nbsp; &nbsp; for (let i = 0; i < 10; i++) {&nbsp; &nbsp; &nbsp; &nbsp; result[i] = i&nbsp; &nbsp; }&nbsp; &nbsp; return result;}var arr = createFunction();console.log(arr);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答