天天看點

javascript中類型的類型判斷

作者:Jsonk
console.log(typeof 11);
console.log(typeof "alex");
console.log(typeof null);
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof [12, 3]);
console.log(typeof { name: "alex" });
console.log(typeof function () { });
console.log(typeof BigInt(123));
console.log(typeof Symbol("Alex"));
// number  能
// string  能
// object  不能
// boolean 能
// undefined能
// object  不能
// object  不能
// function  能
// bigint  能
// symbol  能

// 總結來說typeof隻能判斷對應的基礎值類型原始類型           

以上就是typeof的判斷類型

//原理是判斷在其原型鍊能否找到該類型的原型

var alex = { name: "alex" }
console.log(12 instanceof Number);
console.log("str" instanceof String);
console.log(true instanceof Boolean);
console.log(null == null);
console.log(undefined == null);
console.log(undefined === null);
console.log([1, 2] instanceof Array);
console.log(alex instanceof Object);
console.log(function () { } instanceof Function);

//隻能判斷引用類型原型鍊上
// false
// false
// false
// true
// true
// false
// true
// true
// true
// 注意對應的null的判斷           

以上是instanceof的判斷類型

console.log((2).constructor === Number);
console.log(("str").constructor === String);
console.log((true).constructor === Boolean);
console.log(([]).constructor === Array);
console.log(({}).constructor === Object);
console.log((() => { }).constructor === Function);
// 使用對應的constructor構造函數來判斷對應的是否是對應的引用類型還是原始類型
// 有兩個作用,一是可以判斷類型,二是對象執行個體可以通過範圍constructor來通路到構造函數,如果建立一個對象那個來改變它的原型,那麼就不能判斷類型了

function People(name) {
    this.name = name
}
// 更改對應的原型鍊指向
People.prototype = new Array()
var alex = new People("alex")

// 執行個體對象的constructor指向的是類的prototype
console.log(alex.constructor === People);
console.log(alex.constructor === Array);
           

以上是constructor的判斷類型

//使用Object.prototype.toString判斷資料類型
var a = Object.prototype.toString;

// 包裝類是Number将包裝類轉為字元串
console.log(a.call(2));
console.log(a.call(true));
console.log(a.call('str'));
console.log(a.call([]));
console.log(a.call(function () { }));
console.log(a.call({}));
console.log(a.call(undefined));
console.log(a.call(null));

// [object Number]
// [object Boolean]
// [object String]
// [object Array]
// [object Function]
// [object Object]
// [object Undefined]
// [object Null]
// Object的原型的方法是toString,但是Array和function等類型作為Object的執行個體重寫了toString方法,想要得到對應的具體類型需要調用Object原型的toString方法           

以上是Object.prototype.toString判斷類型,常用的判斷類型方式就這幾種