JavaScript测试(object&& object!=="null"&& object!=="undefined") [英] Javascript test ( object && object !== "null" && object !== "undefined" )

查看:46
本文介绍了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();
}

这篇关于JavaScript测试(object&& object!=="null"&& object!=="undefined")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆