打印函数数组的函数名称

Print function names of an array of functions

本文关键字:函数 数组 打印      更新时间:2023-09-26

假设我有数组[func1, func2, func3]。

我想打印成一个字符串:"func1, func2, func3"。但是,它会打印函数的全部内容。

我是否必须做一些正则表达式才能从输出中获取名称,或者有更简单的方法?

干杯。

使用 Function name 属性:

function doSomething() { }
alert(doSomething.name); // alerts "doSomething"

请注意,根据文档,这在 Internet Explorer 中不起作用。 如果这对您很重要,您可以考虑其他选项。

你想在列表中获取函数名称,对吧?如果是这种情况,这样的事情应该适合你。如果这不是您想要做的,请告诉我。JsFiddle 在这里工作代码

//declare the dummy functions
function funcOne(){
    return null;
}
function funcTwo(){
    return null;
}
function funcThree(){
    return null;
}
//add the functions to the array
var functionArray=[funcOne,funcTwo,funcThree];
//declare an output array so we can then join the names easily
var output=new Array();
//iterate the array using the for .. in loop and then just getting the function.name property
for(var funcName in functionArray){
    if(functionArray.hasOwnProperty(funcName))
        output.push(functionArray[funcName].name);
}
//join the output and show it
alert(output.join(","));