tags:

views:

54

answers:

4

I an creating a querystring from the supplied arguments to Javascript function. I am looping over the arguments array and want to have argumentName and its value.

Thans

A: 

for( var key in array ) ? And then inside that loop array[key] to access the value.

CharlesLeaf
that only works if array is an Object; if it's a plain old array it will "work" but the names will be 0, 1, 2, 3, ... N-1 where N is the function's argument length.
Jason S
The array is this scenario an object because Associative Arrays don't exist in Javascript. With actual arrays you'd still have a normal for loop and already know what the index for each value is. So I don't really appreciate the vote down (whoever gave it).
CharlesLeaf
I guess my point was that the `arguments` variable is not an Object, it's an array. The `array` variable you mention has to come from somewhere + neither you nor the OP mention where it comes from. (fyi the downvote wasn't from me)
Jason S
A: 

I don't think so. the Function class in Javascript has a length property, but there's no way to get the names of the arguments, e.g. x and y in the following

g = function(x,y) { return x+y; }

edit: I guess technically, given a function g you could call

g.toString().match(/function\s+\((.*?)\)/)

which captures the argument list of the function, then parse that to get a list of argument names.

Jason S
OK, whoever -1'd this please give a useful reason.
Jason S
+3  A: 

You need to write the function differently, as it's not possible to do what you're asking, and it doesn't really make any sense, if you think about it; what if your function is invoked with expressions and other function calls in the argument list?

Instead, write a function like this:

function yourFunction(object) {
  for (argName in object) {
    if (object.hasOwnProperty(argName)) {
      var argValue = object[argName];
      // now argName is an argument name, and
      // argValue is the value, and you can do
      // whatever you like
    }
  }
}

When you call the function, you'll do this:

if (whatever)
  yourFunction({ arg1: value1, arg2: value2, arg3: value3 });
Pointy
+1  A: 

No, this not possible, and I'm not sure how you think this might work. If you have named arguments, then you know about the argument names and there's no problem:

function f(arg1, arg2, arg3) {
    var params = {
        arg1: arg1,
        arg2: arg2,
        arg3: arg3
    };
    // Do stuff with params
}

Otherwise, all you have is an array-like collection of values with no names.

Tim Down