I have an array of objects with the following format:
obj = { ref: 8, id: "obj-8" }
and a function which uses jQuery’s grep method to return an item from that array, by searching for the object ref property:
function returnObj(arr,r){
return $.grep(arr, function(elem,index){ return elem.ref == r; })[0];
}
If I use this function on an array that has undefined elements in it (they were previously deleted using the delete operator), I get the following error: Uncaught TypeError: Cannot read property ‘ref’ of undefined, which I assume is thrown when an undefined element is encountered.
How can I modify the function so it doesn’t break?
Just check to see if the current item is
undefined, or simply “falsey” if you expect specifc objects, and returnfalseif so.Here’s another option. Since you’re using
deleteto remove the items, you can use the native.filtermethod, which skips over non-existent array members.