Reputation: 1350
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)?
Upvotes: 1
Views: 59
Reputation: 21
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"});
Upvotes: 0
Reputation: 2856
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" });
Upvotes: 1
Reputation: 63524
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"});
Upvotes: 5
Reputation: 97152
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"});
Upvotes: 4