I'm currently fetching an array with .each:
$.each(messages, function(key,message){ doStuff(); });
But the key is the index of the array and not the associative key.
How can I get it easily?
JavaScript doesn't have "associative arrays". It has arrays:
[1, 2, 3, 4, 5]
And objects:
{a: 1, b: 2, c: 3, d: 4, e: 5}
Array's don't have "keys". They have indices, which are counted starting at 0.
Arrays are accessed using [], and objects can be accessed using [] or ..
Example:
var array = [1,2,3];
array[1] = 4;
console.log(array); // [1,4,3]
var obj = {};
obj.test = 16;
obj['123'] = 24;
console.log(obj); // {test: 16, 123: 24}
If you try to access an array using a string as a key instead of an int, that may cause problems. You would be setting a property of the array and not a value.
var array = [1,2,3];
array['test'] = 4; // This doesn't set a value in the array
console.log(array); // [1,2,3]
console.log(array.test); // 4
jQuery's $.each works with both of these. In the callback for $.each, the first parameter, key, is either the object's key, or the array's index.
$.each([1, 2, 3, 4, 5], function(key, value){
console.log(key); // Logs 0 1 2 3 4
});
$.each({a: 1, b: 2, c: 3, d: 4, e: 5}, function(key, value){
console.log(key); // Logs 'a' 'b' 'c' 'd' 'e'
});
var data = {
val1 : 'text1',
val2 : 'text2',
val3 : 'text3'
};
$.each(data, function(key, value) {
alert( "The key is '" + key + "' and the value is '" + value + "'" );
});
See the Demo
JavaScript doesn't have "associative arrays" as in PHP, but objects. Objects, though, may have string keys that corresponds to a value. Arrays are lists of values indexed numerically, so, if key is a number, it must be an array you are working with and not an object, and therefore you cannot get the key, as there is none.
Thus, you'd probably want to iterate over an array with a simple for-loop instead of a callback-based iterator such as $.each.
messages? post thatvar h = new Array(); h['foo'] = 'bar'. But you didn't added a new array's element, you just added a new property called 'foo'. In fact,alert(h.length)will be0, and you will havealert(h.foo)equals to 'bar'.messagesis, and what values you're looking for?