Access argument name string inside the function

javascript

Solution

You could try something like this:

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

Problem

Is it possible to access arguments name strings?! ``` 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}...] ``` Note: I know using `arguments` is not a good practice. I want to know if this even possible or not?

Original source

Related problems