I have a user that is generating Sentry reports from this code saying Cannot read property 'values' of undefined
var self = this;
if (self.queue()) {
return self.queue().some(function (item, index) {
return item.values[key] == value;
});
} else {
return false;
}
self.queue() is a knockout observable.
How is this possible? Does array.some loop through empty arrays? Or is there some weirdness with observables that the some function is attached to the real array, and the array is being edited while it's being looped through?
The obvious answer is to do this
var self = this;
if (self.queue()) {
return self.queue().some(function (item, index) {
if (item && item.values) {
return item.values[key] == value;
}else{
return false;
}
});
} else {
return false;
}
But I can't see a reason why I should have to do that.
Am I using the some function wrong? Do I need to duplicate the array first before I loop through it?
Thanks
-Edit
This test in node as per GMaiolo's example and Alexey Lebedev's comment
// let arr = [null, undefined, 0, 'something', undefined, 3]
let arr = [null, , , 'something', , 3]
console.log("test 1:");
for (const value of arr) {
console.log(value)
}
console.log("\ntest 2:");
arr.forEach(function(item){
console.log(item);
});
console.log("\ntest 3:");
arr.some(function(item){
console.log(item);
return false;
});
Results
test 1:
null
undefined
undefined
something
undefined
3
test 2:
null
something
3
test 3:
null
something
3
Tested in node 8.11
if (item) {isn't going to stop your error. Ifitemdoesn't have avaluesproperty, or isnull, same error