如何动态获取函数参数名称/值? [英] How to get function parameter names/values dynamically?

查看:157
本文介绍了如何动态获取函数参数名称/值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法动态获取函数的函数参数名?

Is there a way to get the function parameter names of a function dynamically?

假设我的函数如下所示:

Let’s say my function looks like this:

function doSomething(param1, param2, .... paramN){
   // fill an array with the parameter name and value
   // some other code 
}

现在,我如何获得参数名称列表和它们的值从函数内部变成数组?

Now, how would I get a list of the parameter names and their values into an array from inside the function?

推荐答案

以下函数将返回传递的任何函数的参数名数组in。

The following function will return an array of the parameter names of any function passed in.

var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '');
  var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
  if(result === null)
     result = [];
  return result;
}

用法示例:

getParamNames(getParamNames) // returns ['func']
getParamNames(function (a,b,c,d){}) // returns ['a','b','c','d']
getParamNames(function (a,/*b,c,*/d){}) // returns ['a','d']
getParamNames(function (){}) // returns []

编辑

随着ES6的发明,默认参数可以触发此功能。这是一个快速黑客,在大多数情况下应该有效:

With the invent of ES6 this function can be tripped up by default parameters. Here is a quick hack which should work in most cases:

var STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/mg;

我说大多数情况都是因为有些事情会让它绊倒

I say most cases because there are some things that will trip it up

function (a=4*(5/3), b) {} // returns ['a']

编辑
我还注意到vikasde也希望数组中的参数值。这已在名为arguments的局部变量中提供。

Edit: I also note vikasde wants the parameter values in an array also. This is already provided in a local variable named arguments.

摘自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

arguments对象不是Array。它类似于Array,但除了length之外没有任何Array属性。例如,它没有pop方法。但是它可以转换为真正的数组:

The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:

var args = Array.prototype.slice.call(arguments);

如果Array泛型可用,则可以使用以下代码:

If Array generics are available, one can use the following instead:

var args = Array.slice(arguments);

这篇关于如何动态获取函数参数名称/值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆