Javascript 将变量发送到函数的变量?
假设我有一个函数,其中一个参数是目标变量的名称。。我是否可以向函数发送一个变量,如下所示:Javascript 将变量发送到函数的变量?,javascript,Javascript,假设我有一个函数,其中一个参数是目标变量的名称。。我是否可以向函数发送一个变量,如下所示: function otherfunction(input){ ... } function test {target) { var x = 1; target(x); } test(otherfunction); 我遇到的问题是,我正在制作一个greasemonkey脚本,由于受到限制,我需要的一个变量无法从函数返回。。因此,这将是另一种选择。我只是不知道如何让它发挥作用。。任何帮助都将不胜感激 您
function otherfunction(input){
...
}
function test {target) {
var x = 1;
target(x);
}
test(otherfunction);
我遇到的问题是,我正在制作一个greasemonkey脚本,由于受到限制,我需要的一个变量无法从函数返回。。因此,这将是另一种选择。我只是不知道如何让它发挥作用。。任何帮助都将不胜感激 您的示例几乎有效:
function otherfunction(input){
alert(input);
}
function test(target) {
if(typeof target !== 'function') {
alert('target is not a function!');
return;
}
target(1); //invokes the passed-in function, passing in 1
}
test(otherfunction); //alerts 1
//You can also do it with an anonymous function too:
test(function(arg) {
alert(arg * 5);
}); //alerts 5
您的示例几乎有效:
function otherfunction(input){
alert(input);
}
function test(target) {
if(typeof target !== 'function') {
alert('target is not a function!');
return;
}
target(1); //invokes the passed-in function, passing in 1
}
test(otherfunction); //alerts 1
//You can also do it with an anonymous function too:
test(function(arg) {
alert(arg * 5);
}); //alerts 5
你能更精确地说明你的技术限制是什么吗?正如Jacob所概述的,您的问题的正常解决方案是在测试体中调用otherfunction,但这不可避免地会导致调用otherfunction。因此,您也可以只编写OtherFunction 1,而不编写testotherfunction。@J.M请单击空心复选标记内的,接受您问题的正确答案。谢谢你能更精确地说明你的技术限制是什么吗?正如Jacob所概述的,您的问题的正常解决方案是在测试体中调用otherfunction,但这不可避免地会导致调用otherfunction。因此,您也可以只编写OtherFunction 1,而不编写testotherfunction。@J.M请单击空心复选标记内的,接受您问题的正确答案。谢谢