JavaScript中的類型檢查
JS 的動態(tài)類型有好有壞。好的一面,不必指明變量的類型。不好的是,咱們永遠無法確定變量的類型。
typeof運算符可以確定 JS 中的6種類型:
typeof 10; // => 'number'
typeof 'Hello'; // => 'string'
typeof false; // => 'boolean'
typeof { a: 1 }; // => 'object'
typeof undefined; // => 'undefined'
typeof Symbol(); // => 'symbol'
同樣,instanceof 運算符用于檢測構造函數(shù)的 prototype 屬性是否出現(xiàn)在某個實例對象的原型鏈上。
class Cat { }
const myCat = new Cat();
myCat instanceof Cat; // => true
但是typeof和instanceof的一些行為可能會令人混淆。防范于未然,咱們需要提前了解一些邊緣情況。
1. typeof null
typeof myObject === 'object'會告知myObject是否是一個對象類型。舉個例子:
const person = { name: '前端小智' };
typeof person; // => 'object'
typeof person是'object',因為person是一個普通的 JS 對象。
在某場景下,變量值可能需要指定為 null,下面是一些場景:
可以使用null來跳過指示配置對象
使用null初始化稍后要保存對象的變量
當函數(shù)由于某種原因無法構造對象時,返回null
例如,如果不存在正則表達式匹配項,則str.match(regExp)方法返回null:
const message = 'Hello'; message.match(/Hi/); // => null
這里引出一個問題,可以使用typeof 來區(qū)分有值的對象和具有 null 值的對象嗎?
let myObject = null;
typeof myObject; // => 'object'
myObject = { prop: 'Value' };
typeof myObject; // => 'object'
從上面可以看出,typeof 對象有值的對象和具有 null 值的對象,得到的結(jié)果都是'object'。
可以如下面方法來檢測變量是否有對象且不是null:
function isObject(value) {
return typeof value === 'object' && value !== null;
}
isObject({}); // => true
isObject(null); // => false
除了檢查value是否為object: typeof value === 'object'之外,還需要明確地驗證null: value !== null。
2. typeof array
如果試圖檢測一個變量是否包含一個數(shù)組,常見的錯誤就是使用typeof操作符:
const colors = ['white', 'blue', 'red']; typeof colors; // => 'object'
檢測數(shù)組的正確方法是使用Array.isArray():
const colors = ['white', 'blue', 'red'];
const hero = { name: 'Batman' };
Array.isArray(colors); // => true
Array.isArray(hero); // => false
Array.isArray(colors)返回一個布爾值true,表示colors是一個數(shù)組。
3.虛值類型檢查
JS中的undefined是一個特殊值,表示未初始化的變量。
如果試圖訪問未初始化的變量、不存在的對象屬性,則獲取到的值為 undefined :
let city;
let hero = { name: '前端小智', villain: false };
city; // => undefined
hero.age; // => undefined
訪問未初始化的變量 city 和不存在的屬性hero.age的結(jié)果為undefined。
要檢查屬性是否存在,可以在條件中使用object[propName],這種遇到值為虛值或者undefined是不可靠的:
function getProp(object, propName, def) {
// 錯誤方式
if (!object[propName]) {
return def;
}
return object[propName];
}
const hero = { name: '前端小智', villain: false };
getProp(hero, 'villain', true); // => true
hero.villain; // => false
如果對象中不存在propName,則object [propName]的值為undefined。 if (!object[propName]) { return def }保護缺少的屬性。
hero.villain屬性存在且值為false。 但是,該函數(shù)在訪問villan值時錯誤地返回true:getProp(hero, 'villain', true)
undefined是一個虛值,同樣false、0和''和null。
不要使用虛值作為類型檢查,而是要明確驗證屬性是否存在于對象中:
typeof object[propName] === 'undefined' propName in object object.hasOwnProperty(propName)
接著,咱們來改進getProp()函數(shù):
function getProp(object, propName, def) {
// Better
if (!(propName in object)) {
return def;
}
return object[propName];
}
const hero = { name: '前端小智', villain: false };
getProp(hero, 'villain', true); // => false
hero.villain; // => false
if (!(propName in object)) { ... }條件正確確定屬性是否存在。
邏輯運算符
我認為最好避免使用邏輯運算符||作為默情況,這個容易打斷閱讀的流程:
const hero = { name: '前端小智', villain: false };
const name = hero.name || 'Unknown';
name; // => '前端小智'
hero.name; // => '前端小智'
// 不好方式
const villain = hero.villain || true;
villain; // => true
hero.villain; // => false
hero 對象存在屬性villain,值為 false,但是表達式hero.villain || true結(jié)果為true。
邏輯操作符||用作訪問屬性的默認情況,當屬性存在且具有虛值時,該操作符無法正確工作。
若要在屬性不存在時默認設置,更好的選擇是使用新的雙問號(??)操作符,
const hero = { name: '前端小智', villan: false };
// 好的方式
const villain = hero.villain ?? true;
villain; // => false
hero.villain; // => false
或使用解構賦值:
const hero = { name: '前端小智', villain: false };
// Good
const { villain = true } = hero;
villain; // => false
hero.villain; // => false
4. typeof NaN
整數(shù),浮點數(shù),特殊數(shù)字(例如Infinity,NaN)的類型均為數(shù)字。
typeof 10; // => 'number' typeof 1.5; // => 'number' typeof NaN; // => 'number' typeof Infinity; // => 'number'
NaN是在無法創(chuàng)建數(shù)字時創(chuàng)建的特殊數(shù)值。NaN是not a number的縮寫。
在下列情況下不能創(chuàng)建數(shù)字:
Number('oops'); // => NaN
5 * undefined; // => NaN
Math.sqrt(-1); // => NaN
NaN + 10; // => NaN
由于NaN,意味著對數(shù)字的操作失敗,因此對數(shù)字有效性的檢查需要額外的步驟。
下面的isValidNumber()函數(shù)也可以防止NaN導致的錯誤:
function isValidNumber(value) {
// Good
return typeof value === 'number' && !isNaN(value);
}
isValidNumber(Number('Z99')); // => false
isValidNumber(5 * undefined); // => false
isValidNumber(undefined); // => false
isValidNumber(Number('99')); // => true
isValidNumber(5 + 10); // => true
除了typeof value === 'number'之外,還多驗證!isNaN(value)確保萬無一失。
5.instanceof 和原型鏈
JS 中的每個對象都引用一個特殊的函數(shù):對象的構造函數(shù)。
object instanceof Constructor是用于檢查對象的構造函數(shù)的運算符:
const object = {};
object instanceof Object; // => true
const array = [1, 2];
array instanceof Array; // => true
const promise = new Promise(resolve => resolve('OK'));
promise instanceof Promise; // => true
現(xiàn)在,咱們定義一個父類Pet和它的子類Cat:
class Pet {
constructor(name) {
this.name;
}
}
class Cat extends Pet {
sound = 'Meow';
}
const myCat = new Cat('Scratchy');
現(xiàn)在,嘗試確定myCat的實例
myCat instanceof Cat; // => true myCat instanceof Pet; // => true myCat instanceof Object; // => true
instanceof運算符表示myCat是Cat,Pet甚至Object的實例。
instanceof操作符通過整個原型鏈搜索對象的構造函數(shù)。要準確地檢測創(chuàng)建對象的構造函數(shù),需要檢測 constructor 屬性
myCat.constructor === Cat; // => true myCat.constructor === Pet; // => false myCat.constructor === Object; // => false
只有myCat.constructor === Cat的計算結(jié)果為true,表示 Cat 是 myCat實例的構造函數(shù)。
6. 總結(jié)
運算符typeof和instanceof 用于類型檢查。 它們盡管易于使用,但需要注意一些特殊情況。
需要注意的是:typeof null等于'object'。 要確定變量是否包含非null對象,需要顯示指明null:
typeof myObject === 'object' && myObject !== null
檢查變量是否包含數(shù)組的最佳方法是使用Array.isArray(variable)內(nèi)置函數(shù)。
因為undefined是虛值的,所以我們經(jīng)常直接在條件句中使用它,但這種做法容易出錯。更好的選擇是使用prop in object來驗證屬性是否存在。
使用雙問號操作系符號object.prop ?? def 或者 { prop = def } = object 來訪問可能丟失的屬性。
NaN是一個類型為number的特殊值,它是由對數(shù)字的無效操作創(chuàng)建的。為了確保變量有正確的數(shù)字,最好使用更詳細的驗證:!isNaN(number) && typeof number === 'number'。
最后,請記住instanceof通過prototype鏈搜索實例的構造函數(shù)。如果不知道這一點,那么如果使用父類驗證子類實例,可能會得到錯誤的結(jié)果。
代碼部署后可能存在的BUG沒法實時知道,事后為了解決這些BUG,花了大量的時間進行l(wèi)og 調(diào)試,這邊順便給大家推薦一個好用的BUG監(jiān)控工具 Fundebug。
相關文章
JavaScript使用ul中l(wèi)i標簽實現(xiàn)刪除效果
這篇文章主要為大家詳細介紹了JavaScript使用ul中l(wèi)i標簽實現(xiàn)刪除效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04
基于javascript實現(xiàn)checkbox復選框?qū)嵗a
這篇文章主要介紹了基于javascript實現(xiàn)checkbox復選框?qū)嵗a,感興趣的小伙伴們可以參考一下2016-01-01
js操作textarea方法集合封裝(兼容IE,firefox)
在DOM里面操作textarea里面的字符,是比較麻煩的。于是我有這個封裝分享給大家,測試過IE6,8, firefox ,chrome, opera , safari。兼容沒問題。2011-02-02
Some tips of wmi scripting in jscript (1)
Some tips of wmi scripting in jscript (1)...2007-04-04

