loops - Javascript Control many types with "typeof" without "if" -
i wondering if there alternative classic.
if (typeof firstpost === 'object' && typeof firstpost.active === 'boolean' && typeof firstpost.message === 'string' && typeof firstpost.maxheight)
so avoid writing more code, maybe looping object.
i use this:
if user input
var firstpost = { active : true, message : "hello", maxheight : 20 }
then:
var checks = { active : 'boolean', message : 'string', maxheight : 'number' } try { for(var key in checks) { if(typeof firstpost[key] != checks[key]) { throw new error(key + " not " + checks[key]); } } }catch(e) { alert(e.tostring()); }
this not bytesless, it's more clean. (and checks if keys defined)
edit: there no way more compact. can declare function in place , call it.
function checkobject(obj,checks) { for(var key in checks) { if(typeof obj[key] != checks[key]) { return false; } } return true; }
and simply
checkobject(firstpost,{ active : 'boolean', message : 'string', maxheight : 'number' });
you can elaborate return type in order specify error.
Comments
Post a Comment