JS7种基本数据类型
- 六种基本数据类型:
String, Number, Boolean, Null, undefined, symbol
- 一种引用类型:
Object
1.使用js判断数据类型方法
常见的判断方法有
typeof
instanceof
Object.prototype.toString
constructor
duck type
1.1 typeof运算符(常见)
typeof是一种较常见的判断方法,返回的是一个字符串,比较特殊之处在判断Null
类型数据,返回'object'
let a = 'abc'let b = 123let c = truelet d = nulllet e = undefinedlet f = Symbol('abc')console.log('类型a:', typeof a)console.log('类型b:', typeof b)console.log('类型c:', typeof c)console.log('类型d:', typeof d)console.log('类型e:', typeof e)console.log('类型f:', typeof f)
复杂类型Object
,可以判断function
,其他array、object
等会判断为object
如果要判断数组类型,就可以用下面的instanceof
1.2 instanceof(只适用对象类型判断)
用法:
object instanceof constructor
object
表示需要判断的对象,constructor
表示某个构造函数,instanceof
运算符用来检测constructor.prototype
是否存在于参数object
的原型链上。
let a = []let b = function () {}let c = new String()let d = new Number()console.log(a instanceof Array)console.log(b instanceof Function)console.log(c instanceof String)console.log(c instanceof Object)console.log(d instanceof Number)console.log(d instanceof Object)
- 需要注意的是,
String、Number、Date
等对象也是属object
,所以同理,若手写了一个Car
类,那么判断结果就是即属于Car
类,又属于object
function Car(brand, money) { this.brand = brand this.money = money}var mycar = new Car("特斯拉", "30w")console.log(mycar instanceof Car)console.log(mycar instanceof Object)
1.3 Object.prototype.toString(较推荐使用)
这里将call()替换成apply()也是一样的效果,
let a = []let b = function () {}let c = new String()let d = new Number()let e = nulllet f = {}console.log('类型a:', Object.prototype.toString.call(a))console.log('类型b:', Object.prototype.toString.call(b))console.log('类型c:', Object.prototype.toString.call(c))console.log('类型d:', Object.prototype.toString.call(d))console.log('类型e:', Object.prototype.toString.call(e))console.log('类型f:', Object.prototype.toString.call(f))
1.4 constructor
let a = []let b = function () {}let c = new String()let d = new Number()let e = {}let f = nullconsole.log(a.constructor === Array)console.log(b.constructor === Function)console.log(c.constructor === String)console.log(c.constructor === Object)console.log(d.constructor === Number)console.log(d.constructor === Object)console.log(e.constructor === Object)console.log(f.constructor) // 报错
null是无效对象,当然不存在constructor,这节内容强烈推荐阮大大的文章prototype 对象
1.5 duck type
与其说duck type(鸭子类型)是种判断方法,不如是种编程思想,比如不知道一个对象是不是数组,可以判断它的length是不是数字,它是不是有join,push这样的一些数组的方法的等等,通过一些特征判断对象是否属于某些类型