如何在JavaScript中檢查未定義或null變量?

咱們常常在JavaScript代碼中使用如下代碼模式 瀏覽器

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

有沒有更冗長的檢查方法具備相同的效果? 安全

根據一些論壇和文獻的說法,簡單地講,如下應該具備相同的效果。 jsp

if (some_variable)
{
    // Do something with some_variable
}

不幸的是,當未定義some_variable時, Firebug some_variable這樣的語句評估爲運行時錯誤,而第一個語句就能夠了。 這僅僅是Firebug的一種(有害的)行爲,仍是這兩種方式之間確實存在一些區別? 函數


#1樓

我認爲測試「值是否爲nullundefined 」的最有效方法是 性能

if ( some_variable == null ){
  // some_variable is either null or undefined
}

所以,這兩行是等效的: 測試

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

注1 spa

正如問題中提到的那樣,簡短變體要求聲明瞭some_variable ,不然將引起ReferenceError。 可是,在許多用例中,您能夠假定這是安全的: code

檢查可選參數: 對象

function(foo){
    if( foo == null ) {...}

檢查現有對象的屬性 ip

if(my_obj.foo == null) {...}

另外一方面, typeof能夠處理未聲明的全局變量(僅返回undefined )。 正如Alsciende解釋的那樣,出於充分的緣由,這些案例應該減小到最少。

筆記2

這個-甚至更短-的變體並不等效:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

因此

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

注3

一般,建議使用===代替== 。 提議的解決方案是該規則的例外。 爲此, eqnull 語法檢查器甚至提供了eqnull選項。

jQuery樣式指南

應該使用嚴格的相等性檢查(===)來支持==。 惟一的例外是經過null檢查undefined和null時。

// Check for both undefined and null values, for some important reason. undefOrNull == null;

#2樓

因爲沒有一個完整而正確的答案,所以我將嘗試總結一下:

一般,表達式爲:

if (typeof(variable) != "undefined" && variable != null)

沒法簡化,由於可能未聲明該variable所以省略typeof(variable) != "undefined"將致使ReferenceError。 可是, 您能夠根據上下文簡化表達式

若是variableglobal ,則能夠簡化爲:

if (window.variable != null)

若是它是local ,則能夠避免未聲明此變量的狀況,而且還能夠簡化爲:

if (variable != null)

若是它是object property ,則沒必要擔憂ReferenceError:

if (obj.property != null)

#3樓

您必須定義這種形式的功能:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}

#4樓

首先,您必須很是清楚要測試的內容。 JavaScript具備各類隱式轉換,可帶您進入旅途,還有兩種不一樣類型的相等比較器: =====

測試nullundefined的函數test(val)應該具備如下特徵:

test(null)         => true
 test(undefined)    => true
 test(0)            => false
 test(1)            => false
 test(true)         => false
 test(false)        => false
 test('s')          => false
 test([])           => false

讓咱們看看這裏的哪些想法實際上經過了咱們的測試。

這些工做:

val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null

這些不起做用:

typeof(val) === 'undefined'
!!val

我建立了一個jsperf條目來比較這些方法的正確性和性能 。 暫時的結果尚無定論,由於在不一樣的瀏覽器/平臺上運行次數不足。 請花一點時間在計算機上運行測試!

目前,彷佛簡單的val == null測試可提供最佳性能。 它也是最短的。 若是須要補碼,能夠將測試否認爲val != null


#5樓

如答案之一所述,若是您談論的是具備全局做用域的變量,那麼可能會很幸運。 如您所知,您全局定義的變量每每會添加到Windows對象中。 您能夠利用這一事實,所以能夠說您正在訪問一個名爲bleh的變量,只需使用double倒數運算符(!!)

!!window['bleh'];

當還沒有聲明bleh併爲其分配值時,這將返回false。

相關文章
相關標籤/搜索