JavaScript 如何动态获取函数的参数名/值

JavaScript 如何动态获取函数的参数名/值

在本文中,我们给出了一个任意的JavaScript函数,并且任务是返回函数的参数名。

方法: JavaScript包含一个称为 toString() 的方法,用于以字符串表示形式表示函数代码。该方法用于获取参数名/值。

  • 首先,使用toString()方法将函数的代码获取为字符串等效形式。
  • 然后,删除所有不必要的代码,如注释、函数体、空格和ES6箭头(如果有)。
  • 标识第一次出现的'(‘,它将位于参数开始之前。
  • 字符串的最后一个字符将是’)’,它将删除所有注释、函数体、空格和ES6箭头。
  • 同时,最后一个字符将位于参数结束之后。

示例: 此示例解释了上述方法。

// JavaScript program to get the function
// name/values dynamically
function getParams(func) {
 
    // String representation of the function code
    let str = func.toString();
 
    // Remove comments of the form /* ... */
    // Removing comments of the form //
    // Remove body of the function { ... }
    // removing '=>' if func is arrow function 
    str = str.replace(/\/\*[\s\S]*?\*\//g, '')
        .replace(/\/\/(.)*/g, '')
        .replace(/{[\s\S]*}/, '')
        .replace(/=>/g, '')
        .trim();
 
    // Start parameter names after first '('
    let start = str.indexOf("(") + 1;
 
    // End parameter names is just before last ')'
    let end = str.length - 1;
 
    let result = str.substring(start, end).split(", ");
 
    let params = [];
 
    result.forEach(element => {
 
        // Removing any default value
        element = element.replace(/=[\s\S]*/g, '').trim();
 
        if (element.length > 0)
            params.push(element);
    });
 
    return params;
}
 
// Test sample functions
let fun1 = function (a) { };
 
function fun2(a = 5 * 6 / 3, 
b) { };
 
let fun3 = (a, /*
        */
    b, //comment
    c) => /** */ { };
 
console.log(`List of parameters of {fun1.name}:`, 
    getParams(fun1));
console.log(`List of parameters of{fun2.name}:`, 
    getParams(fun2));
console.log(`List of parameters of ${fun3.name}:`, 
    getParams(fun3));

输出

List of parameters of fun1: [ 'a' ]
List of parameters of fun2: [ 'a', 'b' ]
List of parameters of fun3: [ 'a', 'b', 'c' ]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程