function func1() {}
console.log(func1.length);
function func2(a, b) {}
console.log(func2.length);
function fun3(name, age = 18, ...rest) {}
console.log(fun3.length);
复制代码
# 输出结果
0
2
1
三、获取函数参数名称
js复制代码
function test1(a, b, c) {
console.log(a, b, c);
}
console.log(test1.toString());
const test2 = (x, y, z) => {};
console.log(test2.toString());
function test3(name, age = 18, ...rest) {}
console.log(test3.toString());
复制代码
function test1(a, b, c) {
console.log(a, b, c);
}
function param name.html:19 (x, y, z) => {}
function param name.html:23 function test3(name, age = 18, ...rest) {}
js复制代码
function getParamNames(fn) {
const fnStr = fn.toString();
// 匹配参数部分(支持箭头函数和普通函数)
const paramMatch = fnStr.match(/\(([^)]*)\)/);
if (!paramMatch) return [];
// 分割参数并清理空格
const result = paramMatch[1]
.split(",")
.map((param) => param.trim())
.filter((param) => param);
for (let i = 0; i < result.length; i++) {
const param = result[i];
if (param.includes("=")) {
result[i] = param.split("=")[0].trim();
continue;
}
if (param.startsWith("...")) {
result[i] = param.slice(3).trim();
continue;
}
}
return result;
}
function test1(a, b, c) {
console.log(a, b, c);
}
console.log(getParamNames(test1));
const test2 = (x, y, z) => {};
console.log(getParamNames(test2));
function test3(name, age = 18, ...rest) {}
console.log(getParamNames(test3));