js檢測數據類型的方法

  • 2019 年 10 月 8 日
  • 筆記
  • 方式一: typeof
typeof 1;//'number'  typeof true;//'boolean'  typeof '';//'string'  typeof undefined;//'undefined'  typeof function (){};'function'
  • 方式二: instanceof
var arr = [];  arr instanceof Array;//true  arr instanceof Object;//true

但是只要是在原型鏈上出現過構造函數都會返回true,所以這個檢測結果不很準確

  • 方式三: constructor
var arr = [];  arr.constructor === Array;//true  arr.constructor === Object;//false  //因為arr通過原型鏈查找到的constructor指向了Array,所以跟Object判斷就是錯誤滴
  • 方式四: Object.prototype.toString.call() 在Object基本類定義的這個toString()方法,是用來檢測數據類型的; 跟字符串、數字、布爾等原型上定義的toString()方法基本用法都是轉換字符串的。
console.log(Object.prototype.toString.call(1));//[object Number]  console.log(Object.prototype.toString.call(''));//[object String]  console.log(Object.prototype.toString.call(true));//[object Boolean]  console.log(Object.prototype.toString.call(null));// [object Null]  console.log(Object.prototype.toString.call(undefined));//[object Undefined]  console.log(Object.prototype.toString.call([]));// [object Array]  console.log(Object.prototype.toString.call({}));// [object Object]  console.log(Object.prototype.toString.call(/^$/));//[object RegExp]  console.log(Object.prototype.toString.call((function () {})));//[object Function]