开发者

Is there a way to get both the argument name and value while looping over arguments array?

I an creating a querystring from the supplied arguments to Javascript function. I am loopin开发者_StackOverflow社区g over the arguments array and want to have argumentName and its value.

Thans


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 });


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜