JS數(shù)據(jù)類型分類及常用判斷方法
數(shù)據(jù)類型判斷的方法
在探索數(shù)據(jù)類型判斷方法的時候我們需要知道JS中有哪些數(shù)據(jù)類型:
我們可以把JS中數(shù)據(jù)類型分為兩類:
1.基本數(shù)據(jù)類型:Undefined、Null、Boolean、Number、String、Symbol(es6中新增)
2.引用類型(復(fù)雜數(shù)據(jù)類型):里面包含 function、Array、Date 等
判斷數(shù)據(jù)類型的方法有幾種
1.typeof
我相信typeof這個判斷數(shù)據(jù)類型的方法是大家平常用的比較多的,閑話不多說,直接上代碼:
console.log(typeof 1);//number
console.log(typeof 'hello');//string
console.log(typeof true);//boolean
console.log(typeof null);//object
console.log(typeof Symbol(1));//symbol
console.log(typeof undefined);//undefined
console.log(typeof function(){});//function
console.log(typeof []);//object
console.log(typeof {});//object
通過以上代碼和輸出我們大概可以看出,typeof這個判斷能判斷出大部分的數(shù)據(jù)類型,但是基本類型中有null的類型被判斷為object
所以這個判斷還不是那么精確,我們需要其它判斷方法
2.instanceof 用于檢測構(gòu)造函數(shù)的 prototype 屬性是否出現(xiàn)在某個實例的原型鏈上
1.instanceof 左為實例,右為構(gòu)造函數(shù)。即判斷左是不是右的實例對象。內(nèi)部機制是通過原型鏈來判斷的
2.instanceof 可以精準(zhǔn)判斷引用數(shù)據(jù)類型 Array,F(xiàn)unction,Object,而基本數(shù)據(jù)類型不能被 instanceof 精準(zhǔn)判斷,因為它本身不是一個實例對象
console.log(2 instanceof Number);//false
console.log(new Number(2) instanceof Number);//true
console.log('str' instanceof String); //false
console.log(new String('str') instanceof String); //true
console.log([] instanceof Array);//true
console.log([]instanceof Object);//true
console.log({} instanceof Object);//true
console.log({} instanceof Array);//false
console.log(function(){} instanceof Function); // true
在以上代碼中,我們可以看出這個判斷方法還是沒解決實際性的問題,比如我們想判斷null為null,所以接下來介紹一個精確的判斷方法
3.Object.prototype.toString.call()
1.使用 Object 對象的原型方法 toString,使用 call 改變 this 指向
見代碼:
const a = Object.prototype.toString;
console.log(a.call(2)); // [object Number]
console.log(a.call(true)); // [object Boolean]
console.log(a.call('str')); // [object String]
console.log(a.call(Symbol())) // [object Symbol]
console.log(a.call([])); // [object Array]
console.log(a.call(function(){})); // [object Function]
console.log(a.call({})); // [object Object]
console.log(a.call(undefined)); // [object Undefined]
console.log(a.call(null)); // [object Null]
console.log(a.call(new Date())) // [object Date]
console.log(a.call(new Error())) // [object Error]
console.log(a.call(new RegExp())) // [object RegExp
見上面輸出可知,Object.prototype.toString.call()可以判斷出復(fù)雜類型中的Array,F(xiàn)unction,Date等類型,所以我們知道,當(dāng)我們需要判斷復(fù)雜類型時,或者判斷簡單數(shù)據(jù)類型中的null為null時我們可以用次方法,判斷簡單類型中的其他數(shù)據(jù)類型我們可以用typeof來判斷就可以
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
echarts中X軸顯示特定個數(shù)label并修改樣式的方法詳解
最近在使用Echarts圖表遇到些特別的需求,想著給大家整理下,所以下面這篇文章主要給大家介紹了關(guān)于echarts中X軸顯示特定個數(shù)label并修改樣式的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07JS highcharts動態(tài)柱狀圖原理及實現(xiàn)
這篇文章主要介紹了JS highcharts動態(tài)柱狀圖原理及實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10CKEditor擴展插件:自動排版功能autoformat插件實現(xiàn)方法詳解
這篇文章主要介紹了CKEditor擴展插件:自動排版功能autoformat插件實現(xiàn)方法,結(jié)合實例形式詳細分析了CKEditor擴展插件實現(xiàn)自動排版功能的autoformat插件具體定義、配置與使用技巧,需要的朋友可以參考下2020-02-02