Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 3623019

Browse files
committed
fix(forEach): match behaviour of Array.prototype.forEach (ignore missing properties)
Array.prototype.forEach will not invoke the callback function if the properety is not present in the object. Because of this, we have the illusion of not iterating over non-added properties in a sparse array. From ECMAScript: 9. Repeat while k < len a. Let Pk be ToString(k). b. Let kPresent be HasProperty(O, Pk). c. ReturnIfAbrupt(kPresent). d. If kPresent is true, then i. Let kValue be Get(O, Pk) ... (steps for invoking the function and aborting if it throws) Closes #8510 Closes #8522 Closes #8525
1 parent 14b3db3 commit 3623019

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

src/Angular.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -246,8 +246,11 @@ function forEach(obj, iterator, context) {
246246
}
247247
}
248248
} else if (isArray(obj) || isArrayLike(obj)) {
249+
var isPrimitive = typeof obj !== 'object';
249250
for (key = 0, length = obj.length; key < length; key++) {
250-
iterator.call(context, obj[key], key);
251+
if (isPrimitive || key in obj) {
252+
iterator.call(context, obj[key], key);
253+
}
251254
}
252255
} else if (obj.forEach && obj.forEach !== forEach) {
253256
obj.forEach(iterator, context);

test/AngularSpec.js

+10
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,16 @@ describe('angular', function() {
637637
forEach(obj, function(value, key) { log.push(key + ':' + value); });
638638
expect(log).toEqual(['length:2', 'foo:bar']);
639639
});
640+
641+
642+
it('should not invoke the iterator for indexed properties which are not present in the collection', function() {
643+
var log = [];
644+
var collection = [];
645+
collection[5] = 'SPARSE';
646+
forEach(collection, function (item, index) { log.push(item + index); });
647+
expect(log.length).toBe(1);
648+
expect(log[0]).toBe('SPARSE5');
649+
});
640650
});
641651

642652

0 commit comments

Comments
 (0)