[英]How to check for an undefined or null variable in JavaScript?
我們在 JavaScript 代碼中經常使用以下代碼模式
if (typeof(some_variable) != 'undefined' && some_variable != null)
{
// Do something with some_variable
}
是否有更簡潔的檢查方法具有相同的效果?
根據一些論壇和文獻的說法,下面的內容應該具有相同的效果。
if (some_variable)
{
// Do something with some_variable
}
不幸的是,當some_variable
未定義時, Firebug在運行時將這樣的語句評估為錯誤,而第一個就可以了。 這只是 Firebug 的一種(不需要的)行為,還是這兩種方式之間真的存在一些區別?
我認為測試“值為null
或undefined
”的最有效方法是
if ( some_variable == null ){
// some_variable is either null or undefined
}
所以這兩行是等價的:
if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}
注1
如問題中所述,短變體要求已聲明some_variable
,否則將拋出 ReferenceError 。 但是,在許多用例中,您可以假設這是安全的:
檢查可選參數:
function(foo){
if( foo == null ) {...}
檢查現有對象的屬性
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
一般來說,建議使用===
而不是==
。 建議的解決方案是該規則的一個例外。 由於這個原因,JSHint語法檢查器甚至提供了eqnull
選項。
來自jQuery 風格指南:
應該使用嚴格的相等檢查 (===) 來支持 ==。 唯一的例外是在通過 null 檢查未定義和 null 時。
// Check for both undefined and null values, for some important reason.
undefOrNull == null;
編輯 2021-03:
現在大多數瀏覽器都支持Nullish 合並運算符 ( ??
)和Logical nullish assignment (??=)
,如果變量為 null 或未定義,則可以更簡潔地分配默認值,例如:
if (a.speed == null) {
// Set default if null or undefined
a.speed = 42;
}
可以寫成這些形式中的任何一種
a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
您必須區分不同的情況:
undefined
或undeclared 。 如果您在typeof
以外的任何上下文中訪問未聲明的變量,您將收到錯誤消息。if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error
已聲明但未初始化的變量是undefined
。
let foo;
if (foo) //evaluates to false because foo === undefined
未定義的屬性,例如someExistingObj.someUndefProperty
。 undefined 屬性不會產生錯誤,只會返回undefined
,當轉換為布爾值時,其計算結果為false
。 所以,如果你不關心0
和false
,使用if(obj.undefProp)
是可以的。 基於這個事實有一個常見的成語:
value = obj.prop || defaultValue
這意味着“如果obj
具有屬性prop
,則將其分配給value
,否則分配默認值defautValue
”。
有些人認為這種行為令人困惑,認為它會導致難以發現的錯誤,並建議使用in
運算符
value = ('prop' in obj) ? obj.prop : defaultValue
用正常相等檢查 null 也將為未定義返回 true。
if (window.variable == null) alert('variable is null or undefined');
這是唯一應該使用==
和!=
的情況:
if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')
對於任何其他比較,應使用嚴格的比較器( ===
和!==
)。
在 ES5 和 ES6 等較新的 JavaScript 標准中,你可以說
> Boolean(0) //false
> Boolean(null) //false
> Boolean(undefined) //false
all return false,類似於 Python 對空變量的檢查。 因此,如果您想圍繞變量編寫條件邏輯,只需說
if (Boolean(myvar)){
// Do something
}
這里“null”或“empty string”或“undefined”將得到有效處理。
如果你嘗試引用一個未聲明的變量,所有的 JavaScript 實現都會拋出一個錯誤。
對象的屬性不受相同條件的約束。 如果尚未定義對象屬性,則嘗試訪問它時不會引發錯誤。 因此,在這種情況下,您可以縮短:
if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)
至
if (myObj.some_property != null)
考慮到這一點,以及全局變量可以作為全局對象的屬性(瀏覽器的情況下為window
)訪問的事實,您可以將以下內容用於全局變量:
if (window.some_variable != null) {
// Do something with some_variable
}
在本地范圍內,確保在代碼塊的頂部聲明變量總是有用的,這將節省typeof
的重復使用。
首先,您必須非常清楚您測試的內容。 JavaScript 有各種各樣的隱式轉換來絆倒你,還有兩種不同類型的相等比較器: ==
和===
。
測試null
或undefined
的函數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
。
這是使用 Array includes()方法的另一種方法:
[undefined, null].includes(value)
由於沒有一個完整且正確的答案,我將嘗試總結:
一般來說,表達式:
if (typeof(variable) != "undefined" && variable != null)
無法簡化,因為variable
可能未聲明,因此省略typeof(variable) != "undefined"
會導致 ReferenceError。 但是,您可以根據上下文簡化表達式:
如果variable
是global ,您可以簡化為:
if (window.variable != null)
如果它是local ,您可能可以避免未聲明此變量的情況,並且還可以簡化為:
if (variable != null)
如果是對象屬性,就不用擔心ReferenceError:
if (obj.property != null)
這是一個非常罕見的例子,建議使用==
而不是===
。 表達式somevar == null
將為undefined
和null
返回 true ,但對於其他所有內容返回 false (如果變量未聲明,則會出錯)。
正如預期的那樣,使用!=
將翻轉結果。
現代編輯器不會警告將==
或!=
運算符與null
一起使用,因為這幾乎總是所需的行為。
最常見的比較:
undeffinedVar == null // true
obj.undefinedProp == null // true
null == null // true
0 == null // false
'0' == null // false
'' == null // false
自己試試:
let undefinedVar;
console.table([
{ test : undefinedVar, result: undefinedVar == null },
{ test : {}.undefinedProp, result: {}.undefinedProp == null },
{ test : null, result: null == null },
{ test : false, result: false == null },
{ test : 0, result: 0 == null },
{ test : '', result: '' == null },
{ test : '0', result: '0' == null },
]);
您可以檢查變量是否有值。 意義,
if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false
}
如果你不知道一個變量是否存在(也就是說,如果它被聲明了)你應該檢查 typeof 操作符。 例如
if( typeof myVariable !== 'undefined' ) {
// myVariable will get resolved and it is defined
}
與您所擁有的類似,您可以執行類似的操作
if (some_variable === undefined || some_variable === null) { do stuff }
無論yyy是 undefined 還是 null,它都會返回 true
if (typeof yyy == 'undefined' || !yyy) {
console.log('yes');
} else {
console.log('no');
}
是的
if (!(typeof yyy == 'undefined' || !yyy)) {
console.log('yes');
} else {
console.log('no');
}
不
如果 if 語句的目的是在將值分配給變量之前檢查null
或undefined
的值,則可以使用Nullish Coalescing Operator 。 根據caniuse的數據,大約 85% 的瀏覽器應該支持它(截至 2021 年 1 月)。 運算符示例如下所示:
const a = some_variable ?? '';
如果some_variable
為null
或undefined
,這將確保將變量分配給空字符串(或任何其他默認值)。
此運算符最適合您的用例,因為它不會返回其他類型的假值(例如0
和''
的默認值。
如其中一個答案所述,如果您談論的是具有全局范圍的變量,那么您可能會很幸運。 您可能知道,您在全局范圍內定義的變量往往會添加到 windows 對象中。 您可以利用這一事實,假設您正在訪問一個名為 bleh 的變量,只需使用雙反轉運算符 (!!)
!!window['bleh'];
當 bleh 沒有被聲明並賦值時,這將返回一個 false。
為了理解,我們來分析一下 Javascript 引擎在轉換 undefined 、 null 和 ''(也是空字符串)時返回的值是什么。 你可以直接在你的開發者控制台上檢查。
您可以看到所有都轉換為 false ,這意味着所有這三個都假設 javascript '不存在'。 因此,您無需像下面那樣顯式檢查代碼中的所有三個。
if (a === undefined || a === null || a==='') {
console.log("Nothing");
} else {
console.log("Something");
}
另外我想指出一件事。
Boolean(0) 的結果是什么?
當然是假的。 當 0 是您預期結果中的有效值時,這將在您的代碼中創建一個錯誤。 因此,請確保在編寫代碼時檢查這一點。
我已經使用這種方法做到了這一點
將 id 保存在某個變量中
var someVariable = document.getElementById("someId");
然后使用 if 條件
if(someVariable === ""){
//logic
} else if(someVariable !== ""){
//logic
}
在 ES5 或 ES6 中,如果你需要多次檢查,你可以這樣做:
const excluded = [null, undefined, '']; if (!exluded.includes(varToCheck) { // it will bee not null, not undefined and not void string }
這也是一種很好的(但冗長的)方式:
if(someObject.someMember ?? null === null) {
// bladiebla
}
發生的事情非常清楚,而且很難被誤解。 這可能非常重要! :-)
這使用??
運算符( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator )。 如果someObject.someMember
的值為null
或undefined
,則??
運營商啟動並將值null
。
TBH,我喜歡這件事的明確性,但我通常更喜歡someObject.someMember == null
,它更具可讀性和熟練的 JS 開發人員可能知道這里發生了什么。
let varToCheck = ""; //U have to define variable firstly ,or it throw error const excluded = [null, undefined, ""]; if (!excluded.includes(varToCheck)) { // it will bee not null, not undefined and not void string console.log("pass"); } else { console.log("fail"); }
例如,我復制 vladernn 的答案進行測試,您也可以單擊“復制片段以回答”按鈕進行測試。
測試空值( if (value == null)
)或非空值( if (value != null)
)比測試變量的定義狀態更簡單。
此外,如果使用布爾false
值定義變量(或對象屬性),則測試if (value)
(或if( obj.property)
)以確保變量(或對象屬性)的存在會失敗。 買者自負 :)
使用 Ramda,您可以簡單地執行R.isNil(yourValue)
Lodash 和其他幫助庫具有相同的功能。
將 undefined 或 null 或 0 與 ES5 和 ES6 標准進行比較的最佳方法
if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
// do something
}
您必須定義這種形式的函數:
validate = function(some_variable){
return(typeof(some_variable) != 'undefined' && some_variable != null)
}
使用嚴格比較運算符可以輕松區分這兩個值。
示例代碼:
function compare(){
var a = null; //variable assigned null value
var b; // undefined
if (a === b){
document.write("a and b have same datatype.");
}
else{
document.write("a and b have different datatype.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.