简体   繁体   中英

how can I get the name of each argument in the arguments object in javascript

In javascript we have the arguments object that is a not quite array that we can query.

How can I get the name of each argument?

For example if I want to know that the 3rd argument is called embedded for example, how would I discover this?

arguments[2].name == "embedded'

Obviously the above does not work.

I'm afraid that's not possible. Only the values themselves are passed:

function logArguments(){
    for(key in arguments)
        console.log(key, arguments[key]);
}
var someObject = {someProperty:false};

logArguments("1", 3, "Look at me I'm a string!", someObject);
// Returns:
// 0 1
// 1 3
// 2 "Look at me I'm a string!"
// 3 Object {someProperty: false}

So you can only get their array indexes.

You can however, use this for(key in arguments){} to supply as many arguments to a function as you'd want.

The arguments object is a list of parameters, it does not store the name of the arguments.

Some browsers let you use the toString method to get the code of a function:

function a(arg1){}
// undefined
a.toString()
// "function a(arg1){}"

If you need named parameters it's common to pass an object:

$.ajax({
  url: "test.html",
  cache: false
})

I'm not sure what you are trying to achieve... if you use positional arguments and the third argument is called "embedded" then the name of arguments[2] will always be "embedded". But while you know that when writing the code the name of the arguments aren't stored anywhere where you can conveniently access them.

something like this

function a() {
    var arr = Array.prototype.slice.call(arguments, 0, arguments.length);
    for (var aux in arr) {
        alert(aux + ":" + arguments[aux]);
    }
}

src: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM