How to get function parameter names/values dynamically?

前端 未结 30 3237
说谎
说谎 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:36

    The answer to this requires 3 steps:

    1. To get the values of the actual parameters passed to the function (let's call it argValues). This is straight forward as it will be available as arguments inside the function.
    2. To get the parameter names from the function signature (let's call it argNames). This not as easy and requires parsing the function. Instead of doing the complex regex yourself and worrying about edge cases (default parameters, comments, ...), you can use a library like babylon that will parse the function into an abstract syntax tree from which you can obtain the names of parameters.
    3. The last step is to join the 2 arrays together into 1 array that has the name and value of all the parameters.

    The code will be like this

    const babylon = require("babylon")
    function doSomething(a, b, c) {
        // get the values of passed argumenst
        const argValues = arguments
    
        // get the names of the arguments by parsing the function
        const ast = babylon.parse(doSomething.toString())
        const argNames =  ast.program.body[0].params.map(node => node.name)
    
        // join the 2 arrays, by looping over the longest of 2 arrays
        const maxLen = Math.max(argNames.length, argValues.length)
        const args = []
        for (i = 0; i < maxLen; i++) { 
           args.push({name: argNames[i], value: argValues[i]})
        }
        console.log(args)
    
        // implement the actual function here
    }
    
    doSomething(1, 2, 3, 4)
    

    and the logged object will be

    [
      {
        "name": "a",
        "value": 1
      },
      {
        "name": "c",
        "value": 3
      },
      {
        "value": 4
      }
    ]
    

    And here's a working example https://tonicdev.com/5763eb77a945f41300f62a79/5763eb77a945f41300f62a7a

提交回复
热议问题