JS數據類型判斷的幾種方法

JS數據類型判斷

JavaScript 中常見數據類型有Number、String、Boolean、Object、Array、Json、Function、Date、RegExp、Error、undefined、Null等十幾種。ES6還有新增的數據類型有Symbol、Set、Map等。在實際應用中,咱們常常須要判斷數據類型,如今我概括幾種方法,但願對你們有所幫助。javascript

typeof 判斷(最經常使用)

typeof 是 JS 提供的一個運算符,專門用來檢測一個變量的類型 。 typeof 有2種使用方式:typeof(表達式)和typeof 變量名,第一種是對錶達式作運算,第二種是對變量作運算。java

function doSomething() {
    console.log('Hello World!');
}
console.log(typeof 1); // number
console.log(typeof 'Hello'); // string
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof doSomething); // function
console.log(typeof true); // boolean
console.log(typeof new Date()); // object
console.log(typeof new RegExp()); // object
console.log(typeof JSON.stringify({
    name: 'zhencanhua'
})); // string
console.log(typeof null); // object
console.log(typeof undefined); // undefined
console.log(typeof (new Error('error!'))); // object

console.log(typeof a); // undefined
console.log(typeof Symbol()); // symbol
console.log(typeof new Set()); // object
console.log(typeof new Map()); // object

從上面打印結果能夠看出,typeof 不能區分引用型數據的類型和 null。另咱們可使用 Array.isArray(arr) 將數組類型的數據從中篩選出來。數組

instanceof 判斷(瞭解)

instanceof 用來檢測構造函數的 prototype 屬性是否出如今某個實例對象的原型鏈上。 語法:object(實例對象) instanceof constructor(構造函數)。是的話返回 true,不然返回 false。因此, instanceof 運算符只能用做對象的判斷。 針對 typeof 不能判斷的引用型數據,咱們可使用 instanceof 運算符。函數

let arr1 = [1, 2, 3];
let obj1 = {
    name: '小明'
};
function Persion() { }
let persion1 = new Persion();
console.log(arr1 instanceof Array); // true
console.log(arr1 instanceof Object); // true,Array 是Object的子類
console.log(obj1 instanceof Object); // true
console.log(obj1 instanceof Array); // false
console.log(Persion instanceof Function, Persion instanceof Object); // true true
console.log(null instanceof Object); // false
console.log(persion1 instanceof Persion, persion1 instanceof Function, persion1 instanceof Object); // true false true
// String對象和Date對象都屬於Object類型
let str1 = 'Hello';
let str2 = new String();
let str3 = new String('你好');
let myDate = new Date();
console.log(str1 instanceof String, str1 instanceof Object); // false, false
console.log(str2 instanceof String, str2 instanceof Object); // true, true
console.log(str3 instanceof String, str3 instanceof Object); // true, true
console.log(myDate instanceof Date, myDate instanceof Object); // true, true

從上面的判斷能夠看出,instanceof 的使用限制不少,並且還不能很清晰方便的判斷出一個實例是數組仍是對象或方法。this

針對上面方法的弊端,咱們可使用 Object.prototype上的原生toString()方法來檢測數據的類型。prototype

Object.prototype.toString.call() 判斷(最靠譜)

Object 是 JS 提供的原生對象, Object.prototype.toString對任何變量都會返回這樣一個字符串"[object class]",class 就是 JS 內置對象的構造函數的名字。 call是用來改變調用函數做用域的。code

Object.prototype.toString() 在toString方法被調用時執行下面的操做步驟:對象

  1. 獲取this對象的[[Class]]屬性的值。(因此使用call來改變this的指向)ip

  2. 將字符串"[object ",第一步獲取的值, 以及 "]"拼接成新的字符串並返回。原型鏈

[[Class]]是一個內部屬性,全部的對象(原生對象和宿主對象)都擁有該屬性。在規範中,[[Class]]是這麼定義的: 內部屬性的描述, [[Class]] 是一個字符串值,代表了該對象的類型。

讀了上面的說明,用 call 的關鍵地方就在第1步,獲取的是 this 對象,不加 call 改變做用域時 this 指向的是Object.prototype。

function doSomething() {
    console.log('Hello World!');
}
// 使用Object.prototype.toString.call來判斷
console.log(Object.prototype.toString.call(1)); // [object Number]
console.log(Object.prototype.toString.call('Hello')); // [object String]
console.log(Object.prototype.toString.call(false)); // [object Boolean]
console.log(Object.prototype.toString.call({})); // [object Object]
console.log(Object.prototype.toString.call([1, 2, 3])); // [object Array]
console.log(Object.prototype.toString.call(new Error('error!'))); // [object Error]
console.log(Object.prototype.toString.call(new Date())); // [object Date]
console.log(Object.prototype.toString.call(new RegExp())); // [object RegExp]
console.log(Object.prototype.toString.call(doSomething)); // [object Function]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call(undefined)); // [object Undefined]
console.log(Object.prototype.toString.call(JSON.stringify({
    name: 'zhencanhau'
}))); // [object String]
console.log(Object.prototype.toString.call(Math)); // [object Math]
console.log(Object.prototype.toString.call(Symbol('abc'))); // [object Symbol]
console.log(Object.prototype.toString.call(new Set())); // [object Set]
console.log(Object.prototype.toString.call(new Map())); // [object Map]

但在實際應用時咱們只想獲取返回的結果中數組的第二項,好比"[object Number]",咱們只想要Number這段字符,那麼咱們能夠寫個函數進行過濾:

// 經過定義一個公共函數獲取數據類型
function getTypeName(val) {
    let str = Object.prototype.toString.call(val);
    return /^\[object (.*)\]$/.exec(str)[1];
}
console.log(getTypeName(false)); // Boolean
console.log(getTypeName()); // Undefined
console.log(getTypeName(null)); // Null

上面的問題完美解決。

constructor 判斷(比較經常使用)

每個對象實例均可以經過 constrcutor 對象來訪問它的構造函數 。JS 中內置了一些構造函數:Object、Array、Function、Date、RegExp、String等。咱們能夠經過數據的 constrcutor 是否與其構造函數相等來判斷數據的類型。

var arr = [];
var obj = {};
var date = new Date();
var num = 110;
var str = 'Hello';
var getName = function(){};
var sym = Symbol();
var set = new Set();
var map = new Map();

arr.constructor === Array; // true
obj.constructor === Object; // true
date.constructor === Date; // true
str.constructor === String; // true
getName.constructor === Function; // true
sym.constructor === Symbol; // true
set.constructor === Set; // true
map.constructor === Map // true

可是這種方式仍然有個弊端,就是 constructor 所指向的的構造函數是能夠被修改的。

function Name(name) {
    this.name = name;
}

function Stuent(age) {
    this.age = age;
}
// 將構造函數Name的實例賦給Student的原型,Student的原型的構造函數會發生改變,將再也不指向自身。
Stuent.prototype = new Name('張三');
Stuent.prototype.constructor === Name; // true
Stuent.prototype.constructor === Stuent; // false

以上就是我在項目中用到過的數據類型的判斷方法,具體使用哪種,還須要根據本身的實際需求來判斷選擇。

相關文章
相關標籤/搜索