【问题标题】:function argument as string but execute as function?函数参数作为字符串但作为函数执行?
【发布时间】: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


【解决方案1】:

如果你将函数封装在一个模块(对象)中,你可以这样调用它:

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

【讨论】:

  • 您不能使用function 作为变量标识符。否则,是的。