Skip to main content

Bug Tracker

Side navigation

#4176 closed bug (fixed)

Opened February 18, 2009 12:22AM UTC

Closed February 18, 2009 02:30AM UTC

Last modified February 18, 2009 02:32AM UTC

jQuery.each() doesn't deal with arrays properly

Reported by: wmleler Owned by:
Priority: major Milestone: 1.3.2
Component: core Version: 1.3.1
Keywords: each array Cc:
Blocked by: Blocking:
Description

If you create an empty array and insert values into it, then use the jQuery.each() utility, it has an extra value with index 0 that was not inserted. Here is code to show the bug:

<code>

$(function () {

var p1 = [];

var p2 = {};

p1[1] = 'one';

p1[2] = 'two';

p2[1] = 'one';

p2[2] = 'two';

$.each(p1, function(i, v) {

$('#output').append('['+i+'] '+v+'<br />');

});

$('#output').append('<br />');

$.each(p2, function(i, v) {

$('#output').append('['+i+'] '+v+'<br />');

});

});

Output is:

[0] undefined

[1] one

[2] two

[1] one

[2] two

Note the extra value in the array with index 0. That should not be there. Tested on Safari and Firefox on Macintosh.

Attachments (1)
  • bug1.html (0.9 KB) - added by wmleler February 18, 2009 12:23AM UTC.

    small program to reproduce the bug

Change History (4)

Changed February 18, 2009 12:58AM UTC by dmethvin comment:1

resolution: → worksforme
status: newclosed
jQuery.each
always processes an Array from 0 to length-1. The length property is managed by Javascript so it will equal the value of the highest numeric index plus 1. If you have a truly sparse array, you can always handle it with an object, as your example shows.

Changed February 18, 2009 02:01AM UTC by wmleler comment:2

resolution: worksforme
status: closedreopened

Would be very nice if this were in the documentation. Something on the order of "each() iterates though arrays from 0 to length-1".

Changed February 18, 2009 02:30AM UTC by dmethvin comment:3

resolution: → fixed
status: reopenedclosed

Changed February 18, 2009 02:32AM UTC by wmleler comment:4

Thanks very much!