1、JavaScript有哪些数据类型
基础数据类型:Undefined、Null、Boolean、Number、String、Object、Symbol、BigInt。
复杂数据类型(引用数据类型):Object(Function、Array、Date、RegExp)
2、检测数据类型的方式
(1)typeof
只能判断 数字 布尔值 函数 undefined 判断不了引用数据类型
其中 null 和数组 用typeof 的结果都是 object
console.log(typeof 1); // number
console.log(typeof true); // boolean
console.log(typeof 'hello'); // string
console.log(typeof []); // object
console.log(typeof function(){}); // function
console.log(typeof {}); // object
console.log(typeof undefined); // undefined
console.log(typeof null); // object
(2) instanceof
instanceof 只能判断是否是引用数据类型 (Array Function Bbject)
console.log([] instanceof Array); // true
console.log(function(){} instanceof Function); // true
console.log({} instanceof Object); // true
(3)toString
Object.prototype.toString.call()
Object.prototype.toString.call(1) //[object Number]
Object.prototype.toString.call('hello') //[object String]
Object.prototype.toString.call(true) //[object Boolean]
Object.prototype.toString.call(null) //[object Null]
Object.prototype.toString.call(undefined) //[object Undefined]
Object.prototype.toString.call(Symbol.iterator) //[object Symbol]
Object.prototype.toString.call(/[0-9]{10}/) //[object RegExp]
Object.prototype.toString.call([]) //[object Array]
Object.prototype.toString.call({}) //[object Object]
Object.toString()
Number、String,Boolean,Array,RegExp、Date、Function等内置对象均重写了Object原型上的toString方法,作用为将当前数据类型转为字符串类型。
Number.toString(); // "function Number() { [native code] }"
String.toString(); // "function String() { [native code] }"
Boolean.toString(); // "function Boolean() { [native code] }"
Array.toString(); // "function Array() { [native code] }"
RegExp.toString(); // "function RegExp() { [native code] }"
Date.toString(); // "function Date() { [native code] }"
RegExp.toString(); // "function RegExp() { [native code] }"
Function.toString(); // "function Function() { [native code] }"
3、null和undefined区别
Null 和 Undefined 都是基本数据类型
undefined 代表的含义是未定义
null 代表的含义是空对象。
一般变量声明了但还没有定义的时候会返回 undefined,null主要用于赋值给一些可能会返回对象的变量,作为初始化。