js判斷數據類型

一、typeof 直接返回數據類型字段,但是無法判斷數組、null、對象

typeof 1
"number"

typeof NaN
"number"

typeof "1"
"string"

typeof true
"boolean"

typeof undefined
"undefined"

typeof null
"object"

typeof []
"object"

typeof {}
"object"
其中 null, [], {}都返回 "object"

二、instanceof 判斷某個實例是不是屬於原型

// 構造函數
function Fruit(name, color) {
this.name = name;
this.color = color;
}
var apple = new Fruit("apple", "red");

// (apple != null)
apple instanceof Object // true
apple instanceof Array // false

三、使用 Object.prototype.toString.call()判斷

call()方法可以改變this的指向,那麼把Object.prototype.toString()方法指向不同的數據類型上面,返回不同的結果

function _typeof(obj){
var s = Object.prototype.toString.call(obj);
return s.match(/[object (.*?)]/)[1].toLowerCase();
};

_typeof([12,3,343]);
"array"

_typeof({name: 'zxc', age: 18});
"object"

_typeof(1);
"number"

_typeof("1");
"string"

_typeof(null);
"null"

_typeof(undefined);
"undefined"

_typeof(NaN);
"number"

_typeof(Date);
"function"

_typeof(new Date());
"date"

_typeof(new RegExp());
"regexp"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章