js資料型別檢測工具
阿新 • • 發佈:2021-10-26
js型別檢測
1. typeof:
1 // typeof: js檢測基本資料型別的最佳工具(除了null以外), 還可以檢測引用型別function。 2 // eg: 3 console.log(typeof a); //'undefined' 4 5 console.log(typeof (true)); //'boolean' 6 7 console.log(typeof '123'); //'string' 8 9 console.log(typeof 123); //'number' 10 11 console.log(typeof NaN); //'number' 12 13 console.log(typeofSymbol('hello')); //'symbol' 14 15 let fn = function(){}; 16 console.log(typeof fn); //"function"
2. instanceof:
1 // instanceof:用來鑑別當前引用型別是否是某個給定引用型別(建構函式)的例項(注:這個建構函式除了Object以外, 2 // 因為所有的引用型別的值都是Object的例項),如果是的話返回true; 3 // eg: 4 var obj = function(){}; 5 obj instanceof Function; //true 6 obj = [];7 obj instanceof Array; //true 8 obj = new Date() 9 obj instanceof Date; //true 10 obj = /w/g; 11 obj instanceof RegExp; //true 12 obj = {}; 13 obj instanceof Object; //true 14 // 以上這些都屬於Object的例項
3.Object.prototype.toString.call(obj):
1 // Object.prototype.toString.call(obj):型別檢測界的扛把子,可以精準判斷所傳入引數的資料型別。 2 // eg:3 console.log(Object.prototype.toString.call("jerry"));//[object String] 4 console.log(Object.prototype.toString.call(12));//[object Number] 5 console.log(Object.prototype.toString.call(true));//[object Boolean] 6 console.log(Object.prototype.toString.call(undefined));//[object Undefined] 7 console.log(Object.prototype.toString.call(null));//[object Null] 8 console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object] 9 console.log(Object.prototype.toString.call(function(){}));//[object Function] 10 console.log(Object.prototype.toString.call([]));//[object Array] 11 console.log(Object.prototype.toString.call(new Date));//[object Date] 12 console.log(Object.prototype.toString.call(/\d/));//[object RegExp] 13 console.log(Object.prototype.toString.call(Symbol()));//[object Symbol] 14 function Person(){}; 15 console.log(Object.prototype.toString.call(new Person));//[object Object]