Skip to content

Commit 5dc12bd

Browse files
Handle sparse arrays properly in Array#_each to match behavior with browsers' built-in Array#forEach (and ES5). [#790 state:resolved] (Andriy Tyurnikov, Yaffle, Andrew Dupont)
1 parent 1a5f049 commit 5dc12bd

File tree

3 files changed

+14
-5
lines changed

3 files changed

+14
-5
lines changed

CHANGELOG

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
* Handle sparse arrays properly in `Array#_each` to match behavior with browsers' built-in `Array#forEach` (and ES5). [#790 state:resolved] (Andriy Tyurnikov, Yaffle, Andrew Dupont)
2+
13
* Make `Event.extend` work with legacy IE events in IE 9. (Andrew Dupont)
24

35
* Stop appending `&_=` to the parameters for non-GET Ajax requests in Safari. We no longer support any version of Safari for which this is necessary. [#327 state:resolved] (John-David Dalton, Andrew Dupont)

src/lang/array.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,13 @@ Array.from = $A;
189189
slice = arrayProto.slice,
190190
_each = arrayProto.forEach; // use native browser JS 1.6 implementation if available
191191

192-
function each(iterator) {
193-
for (var i = 0, length = this.length; i < length; i++)
194-
iterator(this[i]);
192+
function each(iterator, context) {
193+
for (var i = 0, length = this.length >>> 0; i < length; i++) {
194+
if (i in this) iterator.call(context, this[i], i, this);
195+
}
195196
}
196197
if (!_each) _each = each;
197-
198+
198199
/**
199200
* Array#clear() -> Array
200201
*

test/unit/array_test.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ new Test.Unit.Runner({
4242
this.assertEnumEqual([], $A(5));
4343
this.assertEnumEqual([], $A(true));
4444
},
45-
45+
4646
testClear: function(){
4747
this.assertEnumEqual([], [].clear());
4848
this.assertEnumEqual([], [1].clear());
@@ -185,5 +185,11 @@ new Test.Unit.Runner({
185185
testConcat: function(){
186186
var args = (function() { return [].concat(arguments) })(1, 2);
187187
this.assertIdentical(1, args[0][0]);
188+
},
189+
190+
testEachOnSparseArrays: function() {
191+
var sparseArray = [0, 1];
192+
sparseArray[5] = 5;
193+
this.assertEqual('[0, 1, 5]', sparseArray.inspect(), "Array#each should skip nonexistent keys in an array");
188194
}
189195
});

0 commit comments

Comments
 (0)