I have an array of objects that may or may not be populated with an array in it’s properties. Calling $.each(x,function(){}) on a null x results in a type error
try{
var a = {};
$.each(a.doesnotexist,function(k,v){})
} catch(e) {
console.log(e.message)
}
I’ve seen suggestions of using $.extend on an empty object and passing that value to $.each(). Both of these seem to work for me and seem simpler, are there any downsides to either?
//some test values, not guaranteed properties are populated
var a = [
{v: [1,2,3,4,5], w: [1,2,3,4,5,6]},
{v: [1,2,3,4,5]},
{w: [1,2,3,4,5]},
{v: [1,2,3], w: []},
{v: null}
];
for (i =0; i < a.length; i++) {if (a[i].v) $.each(a[i].v,function(k,v){});}
for (i =0; i < a.length; i++) {$.each(a[i].v||[],function(k,v){});}
The second seems cleanest to me.
You can make use of the
inoperator to check if a property exists in an object.And, use
instanceofoperator to check against the correct variable type.In contrast to the short-circuit evaluation, this one not susceptible to truthy values.