從最垃圾的方式到最牛逼的方式依次排列為:typeof --> constructor --> instanceof --> toString
1.typeof
檢測(cè)對(duì)象類型太過模糊,function、object、array類型都會(huì)返回object,所以此方法垃圾,但實(shí)用性很強(qiáng),氣場(chǎng)很強(qiáng)大
2.constructor
實(shí)例對(duì)象的構(gòu)造函數(shù) (實(shí)例對(duì)象.constructor),返回構(gòu)造函數(shù),可以分辨出類型
var str = 'abc'; var num = 100; var arr = new Array(); var date = new Date(); alert(str.constructor); alert(num.constructor); alert(arr.constructor); alert(date.constructor);
3.instanceof
判斷一個(gè)對(duì)象是否是一個(gè)構(gòu)造函數(shù)(類)的實(shí)例。注意此方法只能檢測(cè)實(shí)例對(duì)象。返回布爾值
var str=new String('abc'); var num=new Number(100); var arr=new Array(); var date=new Date(); alert(str instanceof String); alert(num instanceof Number); alert(arr instanceof Array); alert(date instanceof Date); alert(str instanceof Object);
4.toString()
最牛逼的五星級(jí)方法,此方法功能強(qiáng)大,既可以進(jìn)制轉(zhuǎn)換,又可以轉(zhuǎn)字符串,使用起來逼格級(jí)高
console.log(Object.prototype.toString.call(5).slice(8,-1)); console.log(Object.prototype.toString.call('abc').slice(8,-1)); console.log(Object.prototype.toString.call(true).slice(8,-1)); console.log(Object.prototype.toString.call(function(){}).slice(8,-1)); console.log(Object.prototype.toString.call([]).slice(8,-1)); console.log(Object.prototype.toString.call({}).slice(8,-1)); console.log(Object.prototype.toString.call(/\d/g).slice(8,-1)); console.log(Object.prototype.toString.call(new Date).slice(8,-1)); console.log(Object.prototype.toString.call(null).slice(8,-1)); console.log(Object.prototype.toString.call(undefined).slice(8,-1)); console.log(Object.prototype.toString.call(Math).slice(8,-1));
// Number // String // Boolean // Function // Array // Object // RegExp // Date // Null // Undefined // Math
相關(guān)推薦:
js數(shù)據(jù)類型檢測(cè)的4種方法
Javascript isArray 數(shù)組類型檢測(cè)函數(shù)_javascript技巧
JavaScript中對(duì)數(shù)據(jù)類型檢測(cè)的方法總結(jié)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com