判斷數據類型 Javascript

數據類型

Javascript中,數據類型分爲兩種,一種爲基本數據類型,另一種爲複雜數據類型。
基本數據類型

String,Number,Undefined,Null,Boolean

複雜數據類型

Object

判斷數據類型

首先,我們定義一些變量,以便讓我們好判斷類型。

var bool = true
var num = 1
var str = 'abc'
var und = undefined
var nul = null
var arr = [1,2,3]
var obj = {name:'haoxl',age:18}
var fun = function(){console.log('I am a function')}

1.typeof

首先,我們嘗試通過typeof來判斷。

console.log(typeof bool);    //boolean
console.log(typeof num);     //number
console.log(typeof str);     //string
console.log(typeof und);     //undefined
console.log(typeof null);    //object
console.log(typeof arr);     //object
console.log(typeof obj);    //object
console.log(typeof fun);    //function

可以看出,我們判斷不出 null,object,array類型,因爲都會表示出爲object.

2.instanceof

console.log(bool instanceof Boolean);  //false
console.log(num instanceof Number);    //false
console.log(str instanceof String);     //false
// console.log(und instanceof undefined);  //報錯,因爲undefined不是對象   
// console.log(null instanceof null);    //報錯,因爲null不是對象   
console.log(arr instanceof Array);     //true   
console.log(obj instanceof Object);    //true  
console.log(fun instanceof Function);  //true
   
var bool2 = new Boolean()
console.log(bool2 instanceof Boolean);// true

var num2 = new Number()
console.log(num2 instanceof Number);// true

var str2 = new String()
console.log(str2 instanceof String);//  true

function Person(){}
var per = new Person()
console.log(per instanceof Person);// true

function Student(){}
Student.prototype = new Person()
var haoxl = new Student()
console.log(haoxl instanceof Student);// true
console.log(haoxl instanceof Person);// true

可以看到,instanceof不能判斷null,undefined兩種類型,並且不是以new的形式創建的基本數據類型也判斷不了,用new聲明的類,可以判斷出多層繼承關係.

3.Object.prototype.toString.call

console.log(Object.prototype.toString.call(bool));//[object Boolean]
console.log(Object.prototype.toString.call(num));//[object Number]
console.log(Object.prototype.toString.call(str));//[object String]
console.log(Object.prototype.toString.call(und));//[object Undefined]
console.log(Object.prototype.toString.call(nul));//[object Null]
console.log(Object.prototype.toString.call(arr));//[object Array]
console.log(Object.prototype.toString.call(obj));//[object Object]
console.log(Object.prototype.toString.call(fun));//[object Function]

function Person(){}
function Student(){}
Student.prototype = new Person()
var haoxl = new Student()
console.log(Object.prototype.toString.call(haoxl));//[object Object]
function Person(){}
function Student(){}
Student.prototype = new Person()
var haoxl = new Student()
console.log(Object.prototype.toString.call(haoxl));//[object Object]

根據MDN,可以查到Object.prototype.toString()用法如下:
在這裏插入圖片描述
它會返回我們想要的類型的字符串形式,因此我們再需要call,apply來傳我們環境,就可以實現判斷類型。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章