How to get function parameter names/values dynamically?

前端 未结 30 2598
说谎
说谎 2020-11-22 00:13

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, par         


        
30条回答
  •  情深已故
    2020-11-22 00:38

    The proper way to do this is to use a JS parser. Here is an example using acorn.

    const acorn = require('acorn');    
    
    function f(a, b, c) {
       // ...
    }
    
    const argNames = acorn.parse(f).body[0].params.map(x => x.name);
    console.log(argNames);  // Output: [ 'a', 'b', 'c' ]
    

    The code here finds the names of the three (formal) parameters of the function f. It does so by feeding f into acorn.parse().

提交回复
热议问题