3

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:
1
  • 1
    its actually an object, not array Commented Aug 4, 2011 at 20:19

2 Answers 2

14

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/

Sign up to request clarification or add additional context in comments.

1 Comment

A funny thing is, when you start this script badly with var obj = []; instead of var obj = {};, you CAN console.log your ?array? with length 0 but having indexed contents, but cannot loop through it as through object with $.each(). Wonder what instace I have really created.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.