如何在JavaScript中检查函数数组中的函数索引 [英] How to check the index of a function in an Array of functions in JavaScript
问题描述
对于JavaScript,我是一个新的水平。
我有一个函数以 y
作为输入,返回一个大小为 y
的数组,该数组几乎具有与元素具有相同的功能。
I am pretty new level to JavaScript.
I have a function taking y
as the input to return an array with size y
which has almost the same functions as the elements.
这是我的代码:
function createArrayOfFunctions(y) {
var arr = [];
for(var i = 0; i<y; i++) {
arr[i] = function(x) {
return x + i);} //Probably this is the issue
}
return arr;
}
var input = "5,3,2";
var [y, n, m] = input.split(",");
console.log("input = " + input);
[y, n, m] = [parseInt(y), parseInt(n), parseInt(m)]
var addArray = createArrayOfFunctions(y);
console.log(addArray[n](m)); //I would like to add up n and m
当我执行代码时, i
保持为5,而不是对arr [0],arr [1],arr [2],arr [3],arr [ 4]。结果,它总是输出 m + y
而不是 n + m
。我尝试使用 indexOF
和 this [i]
来确定函数的索引,但它没有工作。
When I execute the code, the i
keeps at 5 instead of iterating from 0,1,2,3,4 for arr[0],arr[1],arr[2],arr[3],arr[4]. As a result, it always output m+y
instead of n+m
. I have tried to use indexOF
and this[i]
to figure out the index of the functions, but it does not work. Is there any ways for me to do this?
谢谢!
推荐答案
您遇到了范围界定问题。
You've encountered a scoping issue.
这是一个解决方案:
function createArrayOfFunctions(y) {
let arr = [];
for (let i = 0; i < y; i++) {
arr[i] = function(x) {
return x + i;
};
}
return arr;
}
以上使用 let
,它将 i
变量的范围限制为每次循环迭代。
The above uses let
, which scopes the i
variable to each loop iteration.
如果您不能使用 let
由于兼容性,请为每个循环使用IIFE:
If you can't use let
due to compatibility, use an IIFE for each loop:
function createArrayOfFunctions(y) {
var arr = [];
for (var i = 0; i < y; i++) {
(function() {
var _i = i;
arr[_i] = function(x) {
return x + _i;
};
})();
}
return arr;
}
以上代码缓存每个 i
IIFE中每个循环的变量,使其保持作用范围。
The above code caches each i
variable for each loop in an IIFE, which keeps it in scope.
这篇关于如何在JavaScript中检查函数数组中的函数索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!