javascript - Can't understand this simple JavaScript code behavior
问题描述
The following function make_f(n) attempting to return a function such that when the user call it, it prints the numbers n, n-1, .., 0.
The logic is to try build the return function (f) with every iteration but it just print "1" infinity. Why is that and how should I fix it? Thanks.
(You can think of 'write(i)' as 'console.log(i)' if you want.)
function make_f(n) {
var i;
var f;
f = function () { write("0");};
for (i = 1; i <= n ; i++) {
f = function () { write(i.toString()); f();};
}
return f;
}
make_f(10)();
解决方案
Your assumption that f()
would still reference its previous function "version" is invalid because both f
and i
are defined in the function scope (using var
), hence by returning from the outer-most function (as well as inside the loop), f
already points to itself and you're ending-up nowhere.
If you'll use let
instead, your code will work as expected (although it's not a recommended way to achieve whatever is it you're trying to achieve):
function make_f(n) {
var f = function() { console.log(0); };
for (let i = 1; i <= n ; i++) {
let prev = f;
f = function () { console.log(i); prev();};
}
return f;
}
make_f(10)();
推荐阅读
- c# - 如何为 ML.NET 规范化大型分类集的数组
- javascript - 仅渲染数组中对象的特定项
- nestjs - 为什么 .env 未定义?
- postgresql - 如何在postgres的RECURSIVE CTE内的CROSS JOIN LATERAL中应用多个条件
- r - 如果在 R 数据框中找到匹配的文本,则向上移动列
- java - 是否可以在 Spring MVC 中将@pattern 与动态正则表达式一起使用
- dataframe - Spark - 将包含 JSON 字符串的列从 StringType 转换为 ArrayType(StringType())
- email - 如何在 Sitefinity 中配置多个电子邮件(来自电子邮件地址)?
- flutter - 如何在单击按钮2时更改按钮1的背景颜色,反之亦然
- excel - 使用动态范围进行条件数据提取