1

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)?

4
  • 3
    You cannot obtain that information; those symbols (event_1 and event_2) are variable references and have nothing to do with the function invocation process (other than the incidental side effect of their being assigned values by the argument expressions). Commented Jun 25, 2014 at 14:31
  • 3
    You can't, that information isn't passed to the function. The function has no idea you performed an assignment there (which is a bit weird to begin with). You will have to change how the values are passed. Commented Jun 25, 2014 at 14:31
  • Thanks, I will just use a normal object for this. Even it dose not look neat Commented Jun 25, 2014 at 14:46
  • 1
    @Mero: It looks perfectly "neat". Commented Jun 25, 2014 at 14:53

4 Answers 4

5

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"});
Sign up to request clarification or add additional context in comments.

1 Comment

Why would anybody downvote this? It's a constructive addition to the question.
4

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

Comments

1

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

Comments

0

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

1 Comment

Almost but that's not a valid object literal.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.