javascript 判斷數據類型的幾種方法
一、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()方法指向不同的數據類型上面,返回不同的結果
Object.prototype.toString.call(1)
"[object Number]"
Object.prototype.toString.call(NaN);
"[object Number]"
Object.prototype.toString.call("1");
"[object String]"
Object.prototype.toString.call(true)
"[object Boolean]"
Object.prototype.toString.call(null)
"[object Null]"
Object.prototype.toString.call(undefined)
"[object Undefined]"
Object.prototype.toString.call(function a() {});
"[object Function]"
Object.prototype.toString.call([]);
"[object Array]"
Object.prototype.toString.call({});
"[object Object]"