简体   繁体   中英

How can I get the name of the key from object arguments in javascript

Lets say I have a function look like this:

function foo()
{
  console.log(arguments);  
}

foo(event_1="1", event_2="2");

In this case the output will be:

[object Arguments] {
 0: "1",
 1: "2"
 }

How can I get the key of the arguments (event_1, event_2) instead of (0,1)?

Similarly to @Robby's answer, you can also use Object.keys :

function foo() {
  console.log(Object.keys(arguments[0]));
}

foo({event_1:"1", event_2: "2"});

Pass your argument as an object, and loop over the object's property names:

function foo() {
  for (var key in arguments[0]) {
    console.log(key);
  }  
}

foo({event_1: "1", event_2: "2"});

In this case 0 and 1 are indeed the keys of the arguments. With event_1="1" you are not passing a key to the function, but assigning the value "1" to a variable event_1 and then passing the value to the function.

If you need to pass key/value-pairs you can use the an object instead:

function foo(data)
{
    for (var key in data)
    {
        console.dir("key="+key+", value="+data[key]);
    }
}

foo({ first: "hello", second: "bye" });    

I don't know if this will help you but you can use an object. Something like this:

function foo(anobj)
{
  console.log(anobj.event_1, anobj.event_2);  
}

foo({event_1:"1", event_2:"2"});

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