- js的数据可分为两大类:
1)基本数据类型:String,Number,Boolean,Null,Undefined,Symbol(ES6新加入)
2)引用数据类型:Object,Array,Function
由于js是一门弱类型语言,变量的类型根据所赋值的类型而变化
例:
let b=1;//b为number类型
let c='你好';//c为string类型
let d=true;//d为Boolean类型
let e=null;//e为null类型
let f=function(){}//f为函数类型
-
判断数据类型的三种方式
1)typeof:
可以看出typeof判断null时会判断成object,,所以这可以说是js的一个小‘bug’,所以判断一个变量是否为null时不能用typeof这种方式,,,除此之外,typeof还会把Array类型判断为object,,记住这两种特殊情况!!2)instanceof:专门判断引用数据类型
用法:a instanceof b(a是否为b类型)
let a=[2];
let b={
name:'curry'
}
let c=function(){
console.log(11);
}
console.log(a instanceof Array);//true
console.log(b instanceof Object);//true
console.log(c instanceof Function);//true
console.log(a instanceof Object);//true
console.log(c instanceof Object);//true
由于数组和函数都属于对象的一种,所以判断Object是都为true
3)使用Object.prototype.toString.call()
Object.prototype.toString.call('') ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用
4)只判断是否为数组类型时还可以用Array.isArray()
这种方法只判断是否为数组,是返回true,否则返回false
let a=[2];
let b={
name:'curry'
}
let c=function(){
console.log(11);
}
console.log(Array.isArray(a));//true
console.log(Array.isArray(b));//false
console.log(Array.isArray(c));//false