Inspect the names/values of arguments in the definition/execution of a JavaScript function

后端 未结 5 1224
北海茫月
北海茫月 2020-11-30 11:03

I\'m looking to do the equivalent of Python\'s inspect.getargspec() in Javascript.

I do know that you can get the arguments list from a Jav

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 11:40

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

    function getParamNames(func) {
        var funStr = func.toString();
        return funStr.slice(funStr.indexOf('(')+1, funStr.indexOf(')')).match(/([^\s,]+)/g);
    }
    

    Example usage:

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

提交回复
热议问题