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

fix(forEach): match behaviour of Array.prototype.forEach (ignore missing properties) #8525

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/Angular.js
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,11 @@ function forEach(obj, iterator, context) {
}
}
} else if (isArray(obj) || isArrayLike(obj)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the check for isArray() is for performance reasons, since isArrayLike() already returns true for arrays?

var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
iterator.call(context, obj[key], key);
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
Expand Down
10 changes: 10 additions & 0 deletions test/AngularSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,16 @@ describe('angular', function() {
forEach(obj, function(value, key) { log.push(key + ':' + value); });
expect(log).toEqual(['length:2', 'foo:bar']);
});


it('should not invoke the iterator for indexed properties which are not present in the collection', function() {
var log = [];
var collection = [];
collection[5] = 'SPARSE';
forEach(collection, function (item, index) { log.push(item + index); });
expect(log.length).toBe(1);
expect(log[0]).toBe('SPARSE5');
});
});


Expand Down