JavaScript 谜题:作用域 [英] JavaScript Puzzle: Scope

查看:45
本文介绍了JavaScript 谜题:作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想弄清楚这个难题:

So I am trying to figure out this puzzle:

function fun1(){
    var result = [];
    for (var i = 0; i < 5; i++){
        result.push( function() {return i} );
    }
    return result;
}

console.log(fun1()[0]()) // returns 5?

那个数组的第一个元素不应该返回一个返回'0'的函数吗?

Shouldn't the first element of that array return a function that returns '0'?

推荐答案

让我们一步一步分解发生的事情:

Let's break down what happens step by step:

  • 我们声明了一个函数fun1(),它返回一个数组result.

for 循环迭代 5 次,每次迭代递增 i.

The for loop iterates 5 times, with each iteration incrementing i.

请注意,返回 i 的匿名函数在整个执行过程中未调用.

Notice that the anonymous function returning i is not invoked throughout the execution.

for 循环以 i 的值为 5 结束.

The for loop ends with the value of i being 5.

调用 fun1()[0] 返回一个数组 result[],该数组有一个函数将 reference 存储到 i,不是 ivalue.

Invoking fun1()[0] returns an array result[] which has a function that stores the reference to i, not the value of i.

然后调用匿名函数跟随该引用并返回i的值,即5.

Invoking the anonymous function then follows that reference and returns the value of i, which is 5.

这篇关于JavaScript 谜题:作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆