javaScript中判断数据类型的方法

一、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的指向是可以改变的

注:本文有借鉴

共同学习,共同进步,知识点不对的请大佬们多多指教✍️

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值