I am using Object.keys to iterate through an object's keys in JS like so:
var cv = view.childViews;
Object.keys(cv).forEach(function(key) {
this.destroyView(cv[key]);
}.bind(this));
however, when cv is undefined or is not an object, Object.keys throws an error. Instead of putting an if statement around Object.keys to check if the typeof cv is an object, is there a native method that is better than Object.keys in that it doesn't throw an error if cv is undefined?
Isn't the whole point of:
Object.keys(cv) vs cv.keys().each()
if cv is null, the first shouldn't throw an error, whereas the latter should. What the heck, thanks JS.
If you don't help me, I will being doing this, much to my own chagrin:
if(typeof cv === 'object'){
Object.keys(cv).forEach(function(key) {
this.destroyView(cv[key]);
}.bind(this));
}
turns out, in ES6, non-object arguments to Object.keys will be "coerced" into an object, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
If you're just iterating, there's good old for...in
for(var i in null){
alert(i);
}
for(var i in undefined){
alert(i);
}
var obj = {hello: 'world'};
for(var i in obj){
alert(i);
alert(obj[i]);
}
I think @Pointy has the right answer so I'll put it here:
Object.keys(cv || {}).forEach(...)
Basically, if cv
is undefined then use a dummy object and do nothing.
One other tactic would be just to do the same in the var
:
var cv = view.childViews || {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With