最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery each function not working for string indexed arrays - Stack Overflow

programmeradmin0浏览0评论

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
Add a comment  | 

2 Answers 2

Reset to default 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/

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.

发布评论

评论列表(0)

  1. 暂无评论