解决方案适用于foreach循环但不适用于for循环
function x(number){
return number - 10;
}
var i = 0
var runtimefunctions = {};
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
for (var key in allLevels) {
runtimefunctions[i] = function() { return x(i); };
i++;
};
console.log(runtimefunctions[1]()); // -6
console.log(runtimefunctions[2]()); // -6
console.log(runtimefunctions[3]()); // -6
Run Code Online (Sandbox Code Playgroud)
努力创造功能,但它是第一次创造这样的东西,所以不能理解正确的方式......
我有一个功能..
function x(number){
return number - 10;
}
runtimefunctions = {};
now I have a loop to run
[1,2,3].forEach(function(y){
//here I want to create a function.. which will make a function x(y) -- like this
runtimefunctions[x] = new Function("return function x_" + levelIterator + "(levelIterator){ console.log(levelIterator); x(" + y + ") }")();
});
Run Code Online (Sandbox Code Playgroud)
所以基本上......想要制作这样的功能.
runtimefunctions= {
"1": x(1),
"2": x(2),
and so on
}
Run Code Online (Sandbox Code Playgroud)
这是你需要的吗?
function x(number){
return number - 10;
}
var runtimefunctions = {};
[1,2,3].forEach(function(y){
runtimefunctions[y] = function() { return x(y); };
});
console.log(runtimefunctions[1]()); // -9
console.log(runtimefunctions[2]()); // -8
console.log(runtimefunctions[3]()); // -7
Run Code Online (Sandbox Code Playgroud)
要满足您的下一个(for-in)要求,您需要使用附加函数调用来关闭索引变量:
var runtimefunctions = {}, i = 0;
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
for (var key in allLevels) {
runtimefunctions[i] = function(index){ return function() { return x(index); } }(i++);
};
Run Code Online (Sandbox Code Playgroud)