views:

1761

answers:

2

Good afternoon. I have an array with some keys, and values in them. I then need to fetch the array keys and not the data in them. I want to do this with jQuery. I know for example that PHP has a function called array_keys(); which takes the array as a parameter and gives you an array back with each key in each index.

This is what I came up with, and it works... the only problem is that it seems so unefficent;

var foo = [];
foo['alfa'] = "first item";
foo['beta'] = "second item";

for (var key in foo) {
 console.log(key);
}

This will output;

alfa
beta

But is there any predefined function for this, as in PHP or any other more effective way of getting this?

+2  A: 

Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way

var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";

for (var key in foo) {
        console.log(key);
}

Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.

EDIT:

In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -

Russ Cam
Thanks for the note, luckily it won't matter for me in this particular case. :) But just one question, why is it better to have it as an object (associative array)?
Stefan Konno
+3  A: 

you can use the each function:

var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
      alert(key)
});

it has several nice shortcuts/tricks: check the gory details here

dfa
and what does $.each() use internally for objects?! This method will be slower because the use of a callback function will increase the length of the scope chain and therefore take longer to resolve the reference to a's properties
Russ Cam