How to get function parameter names/values dynamically?

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

    I'll give you a short example below:

    function test(arg1,arg2){
        var funcStr = test.toString()
        var leftIndex = funcStr.indexOf('(');
        var rightIndex = funcStr.indexOf(')');
        var paramStr = funcStr.substr(leftIndex+1,rightIndex-leftIndex-1);
        var params = paramStr.split(',');
        for(param of params){
            console.log(param);   // arg1,arg2
        }
    }
    
    test();
    

提交回复
热议问题