[英]How to make sure a variable is an object
我已經編寫了一段時間的Javascript,但仍然不太確定我是不是太懶了。 我有很多:
if( typeof( something) === 'undefined' ){
// ..
}
但是,有時候它變得過於冗長。 例如,現在我在做:
var redirectURLs = hotplate.get('hotCoreAuth/redirectURLs/success') || {};
這是因為在以下幾行中我將redirectURLs視為一個對象,盡管它可能根本沒有定義(函數可能會返回undefined
)。
是否有“最佳實踐”備忘單? 我上面寫的是不是太懶了? 只是替代方案很麻煩:
var redirectURLs = hotplate.get('hotCoreAuth/redirectURLs/success');
if( typeof( redirectURLs ) === 'undefined' ){
redirectURLs = {}
}
我意識到快捷方式不那么健壯,但是再一次,人們要么設置了這個值,要么不設置。
想法?
芝加哥商業交易所。
如果您總是希望處理來自外部API的對象(我假設您無法控制hotplate
庫),您可以將每個函數調用包裝為強制轉換為對象。
function getHotplateUri(uri){
// Probably good to validate the URI format
var redirectURLs = hotplate.get(uri);
if( typeof( redirectURLs ) === 'undefined' ){
redirectURLs = {}
}
return redirectURLs
}
使用typeof
,它是一個運算符(不需要括號),檢查變量是否存在 。 短路運算符||
假設變量已經存在(已聲明)並檢查其值是否為falsy(undefined,null,空字符串,零...)。
因此,考慮到這一點,在您的情況下使用typeof
是多余的,因為您正在測試已存在的對象hotplate
的方法的返回值。 如你所說:
...函數可能會返回
undefined
"undefined"
是一種類型,而undefined
是一個預定義的值(類型為"undefined"
)。 它在被提升時被分配給變量,直到分配發生。 如果沒有賦值,則聲明變量但值為undefined
。 還沒有返回任何返回undefined
函數。
所以typeof undefined === 'undefined' // true
當您使用“快捷方式”時,這相當於以下內容:
var redirectURLs = hotplate.get('hotCoreAuth/redirectURLs/success');
if (!redirectURLs) redirectURLs = {};
規范( ECMA-262 )規定邏輯OR運算符( ||
)測試第一個表達式(在本例中為函數調用)是否強制為true - 如果它強制為true,則返回第一個表達式,否則返回第二個。
它還說明了對真與假的強制 ( §9.2 - 請注意,這不是逐字逐句):
假:
- 數字+ 0,-0和NaN
- 空字符串(
""
)false
null
undefined
True:其他一切(包括像
new Boolean(false)
這樣的東西)
所以,如果你不介意讓大多數數字,字符串或價值true
通過,那么邏輯或“快捷方式”將確定。 請注意,如果redirectURLs
為null,您的“詳細”代碼可能會中斷:
var redirectURLs = null;
if (typeof redirectURLs === 'undefined') {
redirectURLs = {};
}
redirectURLs.test = '1'; // TypeError: Cannot set property 'test' of null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.