gpt4 book ai didi

Javascript:在运行时创建函数

转载 作者:行者123 更新时间:2023-11-28 12:17:09 26 4
gpt4 key购买 nike

更新

解决方案适用于 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
<小时/>

努力制作函数,但这是第一次创建这样的东西,所以无法理解正确的方法......

我有一个函数..

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 + ") }")();

});

所以基本上..想要制作这样的功能。

runtimefunctions= {
"1": x(1),
"2": x(2),
and so on
}

最佳答案

这是您需要的吗?

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
<小时/>

为了满足您的下一个(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++);
};

关于Javascript:在运行时创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46914425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com