访问参数名称字符串

访问参数名称字符串

可以访问参数名称字符串吗?

function myFunction (a, b, c, d, e, f) {
    var obj = [];
    [].forEach.call(arguments, function(arg) {
        obj.push({
            // question is how to get variable name here?
            name: "a",// "a", "b", "c", "d", "e", "f"
            value: arg, //a, b, c, ,d, e, f
        })
    });
 return obj;
}

myFunction(1,2,3,4,5,6); // return [{name: "a", value: 1}, {name: "b", value: 2}...]

注意:我知道使用arguments不是一个好习惯。我想知道这是否可能吗?

最佳答案

您可以尝试这样的事情:

function myFunction (a, blabla, c, somethingElse, e, f) {
    var obj = [];
    //'(a, b, c, d, e, f)'
    var tmp = arguments.callee.toString().match(/\(.*?\)/)[0];
    //["a", "b", "c", "d", "e", "f"]
    var argumentNames = tmp.replace(/[()\s]/g,'').split(',');

    [].splice.call(arguments,0).forEach(function(arg,i) {
        obj.push({
            // question is how to get variable name here?
            name: argumentNames[i],
            value: arg
        })
    });
    return obj;
}

console.log(JSON.stringify(myFunction(1, 2, 3, 4, 5, 6)));
//Output-> [{"name":"a","value":1},{"name":"blabla","value":2},
//          {"name":"c","value":3},{"name":"somethingElse","value":4},
//          {"name":"e","value":5},{"name":"f","value":6}]

DEMO

09-19 11:15