我有一个函数(名为“chal”),如果它们不是函数,则只调用console.log()参数,否则调用函数。
function chal(){
for(var i = 0, iLen = arguments.length; i<iLen;i++)
if(typeof arguments[i] == "function")
//if argument is a function, call it
arguments[i]();
else
//if argument is NOT a function, console.log the value
console.log(arguments[i]);
}
我有一个数组(名为“arr”),其中包含一个“AS A STRING”函数
var arr = [
"argumentAsString",
123,
"function(){console.log('this is a function');}"
];
我需要“chal”函数来运行“arr”数组中的参数,但是数组中的字符串函数被调用为函数。
我知道这很令人困惑......这里是jsFiddle:http://jsfiddle.net/YqBLm/1/
我知道它在运行,但实际上遇到了我需要做的事情...我基本上将函数从服务器端传递给客户端作为字符串(function.toString()),现在我需要通过它作为客户端函数的参数......任何人都可以想到什么吗?
提前多多感谢!!
答案 0 :(得分:2)
如果将函数封装在模块(对象)中,则可以这样调用它:
<强>的JavaScript 强>
var module = {
argumentAsString: function(){..}
}
var arr = [
"argumentAsString",
123,
"function(){console.log('this is a function');}"
];
function chal(){
for(var i = 0, iLen = arguments.length; i<iLen;i++)
if(module.hasOwnProperty[arguments[i]])
//if argument is a function, call it
module[arguments[i]]();
else
//if argument is NOT a function, console.log the value
console.log(arguments[i]);
}
修改强>
我可能误解了这个问题! :P
尝试将该函数分配给变量,并将该变量存储在数组中:
var fcn= function(){
console.log('this is a function');
}
var arr = [
"argumentAsString",
123,
fcn
];
编辑2
如果我是对的,以上两个答案都不能解决你的问题。看到类似的问题:Convert string (was a function) back to function in Javascript