JavaScript测试(object&& object!=="null"&& object!=="undefined")
问题描述:
我似乎经常使用此测试
if( object && object !== "null" && object !== "undefined" ){
doSomething();
}
关于 objects
的问题,我从服务调用或读取cookie回来(因为不同的浏览器返回不同的值 null
, undefined
,"null"
或"undefined"
).
on objects
I get back from a service call or from reading cookies (since different browsers return the different values null
, undefined
, "null"
, or "undefined"
).
有没有更简单/更有效的方法来进行此检查?
Is there an easier/more efficient way of doing this check?
答
我认为您不能使它变得更简单,但是您当然可以将该逻辑重构为一个函数:
I don't think you can make that any simpler, but you could certainly refactor that logic into a function:
function isRealValue(obj)
{
return obj && obj !== 'null' && obj !== 'undefined';
}
然后,至少您的代码变为:
Then, at least your code becomes:
if (isRealValue(yourObject))
{
doSomething();
}