js數據類型檢測的四種方式

1.typeof

typeof 用來檢測數據類型的運算符(返回一個字符串,適合函數對象和基本類型的判斷)
   檢測的不論是數組仍是正則都返回的是"object",因此typeof不能判斷一個值是否爲數組
var a = 123;
var b = '123';
var c = false;
var d = null;
var e = undefined;
var f = {};
var g = function(){};
var h = [];
var i = NaN;
​
console.log(typeof a);//number
console.log(typeof b);//string
console.log(typeof c);//boolean
console.log(typeof d);//object
console.log(typeof e);//undefined
console.log(typeof f);//object
console.log(typeof g);function
console.log(typeof h);//object
console.log(typeof i);//number
注:console.log(typeof typeof typeof [12, 23]);//string 兩個或多個typeof一塊兒使用時,返回string

2.instanceof

返回一個布爾值,判斷對象類型(基於原型鏈的方式)
咱們使用instanceof/constructor能夠檢測數組和正則了
原理:
左邊對象的原型鏈(_proto_原型)上是否有右邊構造函數的prototype對象屬性
不適用於基本數據類型。
    var a = 123;
    var b = '123';
    var c = false;
    var d = null;
    var e = undefined;
    var f = {};
    var g = function(){};
    var h = [];
    var i = NaN;
    console.log(a instanceof Number);//false
    console.log(b instanceof String);//false
    console.log(c instanceof Boolean);//false
    console.log(d instanceof Object);//false
    console.log(e instanceof Object);//false
    console.log(f instanceof Object);//true
    console.log(g instanceof Function);true
    console.log(h instanceof Array);//true
    console.log(i instanceof Number);//false NaN是基本數據類型

注意:alert(typeof(null)); //object​ alert(null instanceof Object); //false數組

3.Object.prototype.toString.call()

在Object基本類定義的這個toString()方法,是用來檢測數據類型的;
Object.prototype.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]
注意:IE6/7/8 Object.prototype.toString.call(null/undefined)返回的是[object Object]

4.constructor

var a = 123;
var b = '123';
var c = false;
var d = null;
var e = undefined;
var f = {};
var g = function(){};
var h = [];
var i = NaN;
console.log(a.constructor == Number);//true
console.log(b.constructor == String);//true
console.log(c.constructor == Boolean);//true
// console.log(d.constructor == Object);//true
// console.log(e.constructor == Object);//true
console.log(f.constructor == Object);//true
console.log(g.constructor == Function);//true
console.log(h.constructor == Array);//true
console.log(i.constructor == Number);//true函數

相關文章
相關標籤/搜索