在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ js 如何一句話同時(shí)判斷 undefined null 空 ?

js 如何一句話同時(shí)判斷 undefined null 空 ?

  1. 現(xiàn)在我判斷 變量是否有效是通過(guò)如下的方式(也就是 undefined null '' 各判斷一次 ):
if( (this.$route.query.openid != undefined || this.$route.query.openid != null || this.$route.query.openid != '' ) && window.localStorage.getItem('openid') != '')
{
      ......
 }

想問(wèn)下 JS 或者 Vue 或者 ES 中有沒(méi)有什么方法能一次性直接判斷變量是否有效?

回答
編輯回答
入她眼
  1. 如題僅判斷undefined null ''的話,題主的代碼有誤,最后一個(gè)!=應(yīng)改為!==。其次null==undefined
    (且不==其他任何值)前兩個(gè)僅需保存一個(gè)。
  2. 如果只是3種,則不能通過(guò)!!flagif(flag)判斷,會(huì)發(fā)生隱式類型轉(zhuǎn)換,比如0falseNaN。
2018年2月25日 10:36
編輯回答
夏木

!!this.$route.query.openid

2018年2月16日 03:37
編輯回答
雨蝶

if(condition){} 中,有以下幾種類型會(huì)被判定為假值:

  • null
  • undefined
  • 0
  • ""
  • false
  • void 0
  • NaN

所以不需要像你那樣枚舉:

if(this.$route.query.openid && window.localStorage.getItem('openid'))
{
      ......
 }

然后就是盡量不要用雙等號(hào),盡量用全等號(hào)

2017年7月28日 21:40
編輯回答
失魂人

單就你的問(wèn)題來(lái)說(shuō) if ([null, undefined, ''].indexOf(this.$route.query.openid) > -1)

2018年9月17日 14:33
編輯回答
巴扎嘿

就用if就可以了 if (this.$route.query.openid) 就一定不為空了。

2017年1月14日 00:17
編輯回答
法克魷

樓主采納的 @原罪 的答案不夠準(zhǔn)確,抱著嚴(yán)謹(jǐn)負(fù)責(zé)的態(tài)度,有必要補(bǔ)充說(shuō)明下,首先進(jìn)行一個(gè)判斷的時(shí)候,如果一個(gè)變量是沒(méi)有聲明的是不能直接判斷的,比如下面的判斷會(huì)報(bào)錯(cuò)。

// 在全局域,非方法內(nèi)
if(a) {
    console.log(1)
} else {
    console.log(2)
}
// 會(huì)報(bào)錯(cuò),因?yàn)閍沒(méi)有聲明不能直接調(diào)用

這時(shí)候就要用以下判斷

if(typeof a !== 'undefined' && a !== null) {
    console.log(1)
} else {
    console.log(2)
}
// 是不是要判斷空值(比如false, '', NaN這些的),要看樓主的需求

但是如果一個(gè)變量已經(jīng)聲明過(guò)(不管變量是否被賦值過(guò)),比如在一個(gè)方法內(nèi),

function (a) {
    if(a) {
        console.log(1)
    } else {
        console.log(2)
    }
    // 或者這樣判斷
    if(a != null) {
        console.log(1)
    } else {
        console.log(2)
    }
}

或者這樣的

var a;
if(a) {
    console.log(1)
} else {
    console.log(2)
}

這時(shí)候是沒(méi)有問(wèn)題的

PS:基本上不存在 a == undefined 這樣的判斷,如果是未聲明的undefined, 這樣判斷會(huì)報(bào)錯(cuò), 換成typeof a == 'undefined'。如果是對(duì)象的屬性,直接調(diào)用確實(shí)是undefinde, 但也不會(huì) obj.a == undefinded 判斷,而是直接判斷null,或判斷空值就行 if (obj.a == null)if (obj.a), 注意是兩等號(hào),會(huì)自動(dòng)類型轉(zhuǎn)換,不能三個(gè)等。

2018年5月12日 02:44
編輯回答
款爺
const nullReg = /^(undefined|null|)$/;
if(!nullReg.test(this.$route.query.openid) && !nullReg.test(window.localStorage.getItem('openid'))) {
  ...
}
2017年2月8日 03:55
編輯回答
愚念
var o = {
    a: undefined,
    b: null,
    c: ''
}

function isEmpty (t) {
    return !t;
}

isEmpty(o.a);    // true
isEmpty(o.b);    // true
isEmpty(o.c);    // true

ps 不要自己寫(xiě)判斷 能lodash就lodash

2018年2月14日 20:10