I'm not being able to get the $.each() jquery function working with string indexed arrays, any idea on whats wrong?
Example @ JSFiddle --> /
Code:
var firstArray = [52, 33];
document.writeln("First Array:\n<ul>");
$.each(firstArray, function(key, value)
{
document.writeln('<li>[' + key + ']: ' + value + "</li>\n");
});
document.writeln("</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:
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.writeln("</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:
Share
Improve this question
edited Aug 4, 2011 at 20:25
Andrew Whitaker
126k32 gold badges295 silver badges308 bronze badges
asked Aug 4, 2011 at 20:10
Marcos Roriz JuniorMarcos Roriz Junior
4,10611 gold badges53 silver badges76 bronze badges
1
- 1 its actually an object, not array – Evan Commented Aug 4, 2011 at 20:19
2 Answers
Reset to default 14An 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.