I'm not being able to get the $.each() jquery function working with string indexed arrays, any idea on whats wrong?
Example @ JSFiddle --> http://jsfiddle.net/WKDUA/
Code:
var firstArray = [52, 33];
document.writeln("First Array:\n<ul>");
$.each(firstArray, function(key, value)
{
document.writeln('<li>[' + key + ']: ' + value + "</li>\n");
});
document.writ开发者_Python百科eln("</ul>\n");
var secondArray = new Array();
secondArray['first'] = 'foo';
secondArray['second'] = 'bar';
document.writeln("Second Array:\n<ul>");
$.each(secondArray, function(key, value)
{
document.writeln('<li>[' + key + ']: ' + value + "</li>\n");
});
document.writeln("</ul>\n");
Output:
First Array:
[0]: 52
[1]: 33
Second Array:
An array is always indexed by an integer representing the position of an element.
You're looking for an object whose properties you can access via bracket notation:
var obj = {};
obj['first'] = 'foo';
obj['second'] = 'bar';
document.writeln("Second Array:\n<ul>");
$.each(obj, function(key, value)
{
document.writeln('<li>[' + key + ']: ' + value + "</li>\n");
});
document.writeln("</ul>\n");
In your original code, the $.each
block was never being entered because you did not add any elements to the array. You did define properties first
and second
on that array and assign them values.
Example: http://jsfiddle.net/ddTPu/
String indexed arrays(a.k.a. associative arrays) are objects, and not arrays.
An array cannot have anything than number as indexes(it can even be Math.PI, because it is a number).
The solution is to declare your secondArray as an object :
var secondArray = {};// or var secondArray = new Object();
You can see here a working example.
精彩评论