【发布时间】:2014-01-22 21:01:44
【问题描述】:
我有一个函数(名为“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()) 传递给客户端,现在我需要通过它作为客户端函数的参数...有人能想到什么吗?
提前非常感谢!!
【问题讨论】:
-
您需要eval(),但为什么要将函数作为字符串存储在数组中?
-
@Givi:我不认为你可以将函数作为函数存储在 JS 中的数组中......
-
你可以!
var arr = ["argumentAsString", 123, function(){console.log('this is a function');}]; arr[2]();因为,函数只是对象,您可以将该函数的引用存储在变量、数组或其他对象中。 -
好吧,对不起...我的眼睛欺骗了我...我之前确实想过,但出于某种原因我坚持认为它不起作用...
标签: javascript arrays string function arguments