js 使用Object.toString.call()判断数据类型

使用Object.toString.call()判断数据类型
使用Object.toString.call()可以用来判断:

判断基本数据类型
判断复杂数据类型
判断null和undefined
需要注意的是,Object.prototype.toString 方法返回的字符串格式为 “[object 数据类型]”,其中数据类型和 JavaScript 中的数据类型名称一致。此外,由于该方法是 Object 类型的原型方法,因此需要通过 call 方法来调用,确保 this 指向正确。

const num2 = 0;
console.log('object.toString.call(num2)',Object.prototype.toString.call(num2))//[object Number]

const str1 = '卡卡西'
console.log('object.toString.call(str1)',Object.prototype.toString.call(str1))// [object String]


const obj2 = {name:'佐助',age:'23'}
console.log('object.toString.call(obj2)',Object.prototype.toString.call(obj2))//[object Object]

const arr2 = [1,2,3,4];
console.log('object.toString.call(arr2)',Object.prototype.toString.call(arr2))//[object Array]

const nullValue2 = null
console.log('object.toString.call(nullValue2)',Object.prototype.toString.call(nullValue2))//[object Null]

class Student {
    name;
    constructor(name) {
        this.name = name;
    }

}

const student1 = new Student('周周');
console.log('object.toString.call(student1)',Object.prototype.toString.call(student1))// [object Object]

class Student2 {
    name;
    constructor(name) {
        this.name = name;
    }
    toString(){
        console.log(this.name)
    }
    // 重写 Symbol.toStringTag 属性
    get [Symbol.toStringTag]() {
        return 'Student2';
    }
}

const student2 = new Student2('周周')
console.log('object.toString.call(student2)',Object.prototype.toString.call(student2))// [object Student2]

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值