数据类型
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来传我们环境,就可以实现判断类型。