目录
一、javaScript数据类型
数据类型 | 类型说明 |
---|---|
String—字符串 | 字符串类型String,用单引号或者双引号包裹的任何字符 |
Number—数字 | 只能是数字或者小数 |
Bollean—布尔值 | true或false,真或假 |
Null—空值,是对象类型 | null值表示一个空对象指针 |
Undefined—未定义 | 定义变量后不赋值,这个变量就是undefined |
复杂数据类型—Object | 对象Object、数组Array、函数Function、Date |
二、javaScript判断数据类型的方法
1.使用typeof
console.log(typeof(123))---//number
console.log(typeof('Hello word'))---//string
console.log(typeof(true))---//boolean
console.log(typeof(undefined))---//undefined
console.log(typeof(function(){}))---//function
console.log(typeof(null))---//object
console.log(typeof({}))---//object
console.log(typeof([]))---//object
//typeof后面不加()写法也是正确的
console.log(typeof 123)---//number
【注】:typeof—只能检测基本数据类型,对于null及数组、对象,typeof均检测出为object,不能进一步判断它们的类型。
2.使用instanceof
//语法:(判断的数据类型)instanceof(js中的数据类型)
let obj = {name:'小明',age:19}
let arrList = [1,2]
let fn = function(){}
console.log(obj instanceof Object)---//true
console.log(arrList instanceof Array)---//true
console.log(fn instanceof Function)---//true
console.log('H' instanceof String)---//true
console.log(false instanceof Boolane)---//true
【注】:左边放你要判断的内容,右边放类型来进行JS类型判断,只能用来判断复杂数据类型,因为instanceof 是用于检测构造函数(右边)的 prototype 属性是否出现在某个实例对象(左边)的原型链上。
3.使用Object.prototype.toString.call—万能检测
console.log(Object.prototype.toString.call(123))---//[object Number]
console.log(Object.prototype.toString.call('H'))---//[object String]
console.log(Object.prototype.toString.call(false))---//[object Boolane]
console.log(Object.prototype.toString.call(undefined))---//[object undefined]
console.log(Object.prototype.toString.call(null))---//[object Null]
console.log(Object.prototype.toString.call([1,2,3]))---//[object Array]
console.log(Object.prototype.toString.call({}))---//[object Object]
console.log(Object.prototype.toString.call(function(){}))---//[object Function]
console.log(Object.prototype.toString.call(new Date))---//[object Date]
【注】:在任何值上调用 Object 原生的 toString() 方法,都会返回一个 [object NativeConstructorName] 格式的字符串。每个类在内部都有一个 [[Class]] 属性,这个属性中就指定了上述字符串中的构造函数名。
但是它不能检测非原生构造函数的构造函数名。
4.使用constructor
console.log((123).constructor === Number)---//true
console.log(('H').constructor === String)---//true
console.log((false).constructor === Boolane)---//true
console.log(([1,2,3]).constructor === Array)---//true
console.log((function(){}).constructor === Function)---//true
console.log(({}).constructor === Object)---//true
console.log((new Date).constructor === Date)---//true
【注】:constructor不能判断undefined和null,并且使用它是不安全的,因为contructor的指向是可以改变的
注:本文有借鉴
共同学习,共同进步,知识点不对的请大佬们多多指教✍️