如何在不使用var关键字的情况下编写此代码? [英] How would this code be written without using the var keyword?

查看:91
本文介绍了如何在不使用var关键字的情况下编写此代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用let关键字而不是var关键字,那么如何编写此代码并输出相同的结果



How would this code be written, and output the same result, if you used the let keyword rather than the var keyword

function constfuncs() {
    var funcs = [];
    for(var i = 0; i < 10; i++) 
       funcs[i] = function() { return i; };
    return funcs;
}

var funcs = constfuncs();
console.log(funcs[5]()); //Outputs 10







我尝试过:



我不完全了解JavaScript吊装,所以我想看看这段代码在使用更易理解的变量类型时如何工作




What I have tried:

I don't fully understand JavaScript hoisting, so I wanted to see how this piece of code would work when using a more understandable type of variable

推荐答案

var 声明一个全局变量,而将变量声明为有限范围。在这种情况下,变量的范围在循环内。在循环之外, i 不存在。



如果你将其保留为 var ,变量的范围是结束constfuncs()函数。



参见 this [ ^ ]获取更多信息。
var declares a global variable while let declares a variable to a limited scope. In this case, the scope of the variable is inside the loop. Outside the loop, i doesn't exist.

If you leave this as var, the scope of the variable is the end constfuncs() function.

See this[^] for more information.


这篇关于如何在不使用var关键字的情况下编写此代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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