js数据类型及判断方法

7 篇文章 0 订阅
  1. js的数据可分为两大类:
    1)基本数据类型:String,Number,Boolean,Null,Undefined,Symbol(ES6新加入)
    2)引用数据类型:Object,Array,Function

由于js是一门弱类型语言,变量的类型根据所赋值的类型而变化
例:

let b=1;//b为number类型
let c='你好';//c为string类型
let d=true;//d为Boolean类型
let e=null;//e为null类型
let f=function(){}//f为函数类型
  1. 判断数据类型的三种方式
    1)typeof:
    在这里插入图片描述
    可以看出typeof判断null时会判断成object,,所以这可以说是js的一个小‘bug’,所以判断一个变量是否为null时不能用typeof这种方式,,,除此之外,typeof还会把Array类型判断为object,,记住这两种特殊情况!!

    2)instanceof:专门判断引用数据类型

    用法:a instanceof b(a是否为b类型)

let a=[2];
let b={
    name:'curry'
}
let c=function(){
    console.log(11);
}
console.log(a instanceof Array);//true
console.log(b instanceof Object);//true
console.log(c instanceof Function);//true
console.log(a instanceof Object);//true
console.log(c instanceof Object);//true

由于数组和函数都属于对象的一种,所以判断Object是都为true

3)使用Object.prototype.toString.call()

Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用

4)只判断是否为数组类型时还可以用Array.isArray()
这种方法只判断是否为数组,是返回true,否则返回false

let a=[2];
let b={
    name:'curry'
}
let c=function(){
    console.log(11);
}
console.log(Array.isArray(a));//true
console.log(Array.isArray(b));//false
console.log(Array.isArray(c));//false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值