JS中檢測(cè)數(shù)據(jù)類型的五種方法。

因?yàn)橐郧安皇呛芮宄?,在網(wǎng)上看了一些文章后做了一下總結(jié)。

1.typeof? 這是最常用的基本數(shù)據(jù)類型檢測(cè)的方法

console.log(typeof "");? ? ?// string

console.log(typeof 1);? ? ?// number

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

可以看見,null? ?數(shù)組? ?跟? {}對(duì)象? 都是object? ?是無法區(qū)分的

2.instanceof

console.log("1" instanceof String);? ? ?// false

console.log(1 instanceof Number);? ?// false

console.log(true instanceof Boolean);? ??// false

console.log({} instanceof Object);? ? ?//? true

console.log([] instanceof Array);? ? ?//? true

console.log(function(){} instanceof Function);? ? ?//? true


本方法可以檢測(cè)復(fù)雜數(shù)據(jù)類型

//? ? ? ? ? ? console.log(null instanceof Null);

//? ? ? ? ? ? console.log(undefined instanceof Undefined);

null 跟??undefined? ?直接輸出會(huì)報(bào)錯(cuò)? 但是使用new? 關(guān)鍵字創(chuàng)建就不會(huì)

3.constructor

console.log(("1").constructor === String);? ? //? true

console.log((1).constructor === Number);? ???//? true

console.log((true).constructor === Boolean);? ? ? //? true

console.log(({}).constructor === Object);? ? ? ??//? true

console.log(([]).constructor === Array);? ? ? ??//? true

console.log((function() {}).constructor === Function);? ? ??//? true

//? ? console.log((null).constructor === Null);

//? ? console.log((undefined).constructor === Undefined);

看起來是可以解決所有問題了,但是改原型(prototype)就會(huì)改變類型

4.Object.prototype.toString.call()? ? ? 終極方法,百試不爽

?console.log(Object.prototype.toString.call("1"));? ? //? {object? ? String}

?console.log(Object.prototype.toString.call(1));? ? ??//? {object? ? Number}

console.log(Object.prototype.toString.call(null));? ? ? ? ?//? {object? ? Null}

console.log(Object.prototype.toString.call(undefined));? ? ? ? ?//? {object? ? Undefined}

?console.log(Object.prototype.toString.call(true));? ? ?//? {object? ? Boolean}

?console.log(Object.prototype.toString.call({}));? ? ??//? {object? ? ?Object}

?console.log(Object.prototype.toString.call([]));? ? ? ? ?//? {object? ? Array}

?console.log(Object.prototype.toString.call(function () {});? ? ? ??//? {object? ?Fuction}

就算是更改原型一樣可以輸出 原來的數(shù)據(jù)類型

5.$.type() 或者? jQuery.type()? ?常用的jQuery方法,實(shí)質(zhì)就是第四種方法,使用簡(jiǎn)便,但是需要引入jQuery

$.type("1")? ? ??//? {object?String}

$.type(1)? ? ??//? {object?Number}

$.type([])? ??//? {object? ? Array}

$.type(undefined)? ??//? {object?Undefined}

$.type(null)? ???//? {object? ? Null}

就列舉幾個(gè)了,輸出同方法四相同

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容