1

假设你有

var funct=function(a,b){
    return a+b;
};
console.log(funct);

有什么方法可以从函数中获取参数(a 和 b)的名称?如果您使用该功能,您可以访问它们吗?我知道“参数”为您提供了一个类似数组的对象,但是有没有什么可以为您提供类似地图或类似对象的参数表示,以便您可以在声明函数时获取它们的名称?

4

2 回答 2

5

不,你不能这样做。没有办法将变量的名称作为字符串获取。

如果你真的需要这个,我建议不要传递多个参数,而是传递一个对象。

var funct=function(args){
    var argsNames = Object.keys(args); // Get the keys of the args object
    console.log(argsNames); // ['a','b']
    return args.a + args.b;
};

然后像这样调用它:

funct({
    a: 12,
    b: 2
});
于 2012-06-14T16:05:10.557 回答
2

一种方法是将函数转换为字符串并解析出来

var funct=function(a,b){
    return a+b;
};
var re = /\(([^)]*)/;
var daArgs = funct.toString().match(re)[1].split(/,\s?/);
console.log(daArgs);

jsFiddle

仍然不知道为什么需要它。

于 2012-06-14T16:08:10.580 回答