易错点:
1、要记住typeof null的结果是object
2、容易漏掉es6的类型,这样会让面试官觉得你缺乏技术深度
JavaScript的数据类型有两类,基本数据类型和复杂数据类型
- 值类型(基本数据类型)有:
string(字符串),number(数字),boolean(布尔),undefined(未定义),null(对空),bigint,symbol
这里面的bigint是因为number类型受限于双精度浮点数的问题 ,它只能表示-(253-1)到(253-1)之间的数字,一旦在这个范围之外就会出现精度丢失的问题,所以会有bigint的类型出现,并且bigint不能和number进行运算操作,否则会报错。
注意:symbol是ES6引入了一种新的原始数据类型,表示独一无二的值,所以他经常被用作对象的key。 - 引用数据类型(对象类型):object(对象),Array(数组),Function(函数)
JavaScript如何判断类型
- typeof
typeof是JavaScript里面的一个操作符,他的使用方式是typeof××× ,他的返回值有以下这些:
string,number,boolean ,bigint,symbol,undefined,object,function。
注意:typeof null返回object。并且typeof无法区分数组、Date等这种对象。
判断一个变量是否被声明可以用(typeof变量===“undefined”)来判断
typeof 1 //"number"
typeof 'a' //"string"
typeof true //"boolean"
typeof undefined // "undefined"
typeof Symbol() //"symbol"
typeof 42n // "bigint"
typeof null //"object"
typeof NaN // "number"
typeof ({a:1}) //"object" 普通对象直接返回object
typeof [1,3] // 数组返回"object"
typeof(new Date) //内置对象"object"
typeof function(){} // "function"
- instanceof
A instanceof B 用来判断A是不是B的实例,B是构造函数,只能用来判断复杂数据类型,因为instanceof用于检测构造函数B的prototype属性是否出现在某个实例对象A的原型链上。
const obj={}
obj instanceof Object // true
const arr=[]
arr instanceof Array // true
function Car(){}
const car =new Car()
car instanceof Car // true
(new Date) instanceof Date // true
如果修改了car实例的原型链, car instanceof Car就会返回false。
function Car {}
const car =new Car();
console.log(car instanceof Car) // true
car._proto_=null;
console.log(car instanceof Car) // false
- constructor属性
JavaScript中的对象会从他们的原型链上集成constructor属性,这个属性指向了创建对象的构造函数本身,所以我们可以通过constructor来判断数据类型。
const obj={}
obj.constructor===Object // true
const arry=[]
arry.constructor===Array // true
const number=1
number.constructor===Number // true
注意:null和undefined没有constructor属性,所以不能使用constructor来判断类型。
- toString方法
toString方法是从Object上继承下来的方法,这个方法一般这样调用:
object.prototype.toString.call(×××)
他返回"[object, 类型]",
注意:返回的格式及大小写,前面是小写,后面是首字母大写。
Object.prototype.toString.call(999) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"
Object.prototype.toString.call(42n) // "[object BigInt]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(true) // "[object Boolean]
Object.prototype.toString.call({a:1}) // "[object Object]"
Object.prototype.toString.call([1,2]) // "[object Array]"
Object.prototype.toString.call(new Date) // "[object Date]"
Object.prototype.toString.call(function(){}) // "[object Function]"
Object.prototype.toString.call(window) // "[object Window]"
Object.prototype.toString.call(document)// "[object HTMLDocument]"
Object.prototype.toString.call(new RegExp()) //'[object RegExp]'
Object.prototype.toString.call(new Error) //[object Error]