JavaScript中如何判斷一個值的類型
我們知道在js中有一個運算符可以幫助我們判斷一個值的類型,它就是typeof運算符。
console.log(typeof 123); //number console.log(typeof '123'); //string console.log(typeof true); //boolean console.log(typeof undefined); //undefined console.log(typeof null); //object console.log(typeof []); //object console.log(typeof {}); //object console.log(typeof function() {}); //function
我們從以上結果可以看出typeof的不足之處,它對于數(shù)值、字符串、布爾值分別返回number、string、boolean,函數(shù)返回function,undefined返回undefined,除此以外,其他情況都返回object。
所以如果返回值為object,我們是無法得知值的類型到底是數(shù)組還是對象或者其他值。為了準確得到每個值的類型,我們必須使用js中另一個運算符instanceof。下面簡單的說一下instanceof的用法。
instanceof運算符返回一個布爾值,表示指定對象是否為某個構造函數(shù)的實例。
instanceof運算符的左邊是實例對象,右邊是構造函數(shù)。它會檢查右邊構造函數(shù)的ptototype屬性,是否在左邊對象的原型鏈上。
var b = []; b instanceof Array //true b instanceof Object //true
注意,instanceof運算符只能用于對象,不適用原始類型的值。
所以我們可以結合typeof和instanceof運算符的特性,來對一個值的類型做出較為準確的判斷。
//得到一個值的類型 function getValueType(value) { var type = ''; if (typeof value != 'object') { type = typeof value; } else { if (value instanceof Array) { type = 'array'; } else { if (value instanceof Object) { type = 'object'; } else { type = 'null'; } } } return type; } getValueType(123); //number getValueType('123'); //string getValueType(true); //boolean getValueType(undefined); //undefined getValueType(null); //null getValueType([]); //array getValueType({}); //object getValueType(function(){}); //function
總結
以上所述是小編給大家介紹的JavaScript中如何判斷一個值的類型,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
JavaScript操作localStorage實現(xiàn)保存本地json文件
這篇文章主要為大家詳細介紹了JavaScript如何操作localStorage實現(xiàn)保存本地json文件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-02-02用js實現(xiàn)before和after偽類的樣式修改的示例代碼
本篇文章主要介紹了用js實現(xiàn)before和after偽類的樣式修改的示例代碼,具有一定的參考價值,有興趣的可以了解一下2017-09-09