3

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?

2
  • How could myFunction return anything if it doesn't have a return statement? Commented Jun 25, 2012 at 17:28
  • I have yet to find a basic way to retrieve the names of the argument variables. Values is cake, names not so much. Commented Jun 25, 2012 at 17:36

6 Answers 6

6

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

Sign up to request clarification or add additional context in comments.

11 Comments

Nice hack. callee is what I never thought about.
Yep, I agree. But consider reading developer.mozilla.org/en/JavaScript/Reference/… too
@KooiInc Yes, callee is forbidden only in strict mode, but not in entire javascript at all.
+1 For finding a creative solution, though I'd agree that .callee shouldn't be used when you could use the function name.
@Engineer, it's not forbidden in non strict js, but it is deprecated for a number of reasons, very well explained here: stackoverflow.com/questions/103598/….
|
2

Are the function parameter names definied in the function definition, as you've written above? If so, you can just create an array in the function:

function myFunction(a,b,c,d,e,f) {
  var argNames = ['a','b','c','d','e','f'];
  ...
}

arguments will only ever contain a simple array of the arguments passed to the function. There is no default mapping from arguments to parameter names. That I'm aware of anyway

1 Comment

Yes, but you don't have any choice in the matter. There's no practical way to access function parameter names. Maybe you can clarify the context in which you're attempting this; perhaps there is a better solution?
0

This works:

function myFunction( _obj ) {

    var obj = [],
        names = [],
        args = arguments,
        len = function(o) {
            var a = [];

            for (var i in o) a.push(i);

            return a;
        };

    for (var i in _obj) names.push( i );

    [].forEach.call( len(_obj), function(a, b) {
        obj.push({
            name: names[b],
            value: args[0][names[b]]
        });
    });

    return obj;

}

console.log( myFunction({
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6
}));​​​​

Here is a DEMO

4 Comments

He wants the name, so the first argument would have name:"a", then name:"b", name:"c", etc. You're assigning "a" for every argument.
@Mohsen I was able to change it. Instead of inputting the arguments individually, I made it able to take an object literal instead. This version does work.
Sorry, you have changed the question.
What do you mean, this functions as you have intended?
0

For completeness: you can't use named parameters in javascript. If you want to use them (and thus be able to identify the parameter names), a workaround is to supply an object:

function myParams(params){
  var ret = [];
  for (var l in params){ 
   if (params.hasOwnProperty(l)){
    ret.push(l);
   }
  }
  return ret
}
myParams({a:1,b:2,c:3,d:null,e:null,f:null,g:11});
//=> [a,b,c,d,e,f,g]

See also...
And to be really complete: see this also

Comments

0

You can invoke toString on the function and then use some kind of RegEx to parse result.



    function someFunction(a,b,c){}
    var functionString = someFunction.toString(); //return "function someFunction(a,b,c){}"
    var args = functionString.match(/^function (?:.*?)\((.*?)\)/);
    if(args[1])
    {
        var argsNames = args[1].split(",");
    }


I've tested it on FF and Chrome.

Comments

0

Since item.product_image2 is a URL string, you need to put it in quotes when you call changeImage inside parameter.

My Function Onclick

items+='<img src='+item.product_image1+' id="saleDetailDivGetImg">';
items+="<img src="+item.product_image2+"  onclick='changeImage(\""+item.product_image2+"\");'>";

My Function

<script type="text/javascript">
function changeImage(img)
 {
    document.getElementById("saleDetailDivGetImg").src=img;
    alert(img);
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.