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

发布于:2024-04-20 ⋅ 阅读:(14) ⋅ 点赞:(0)

使用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]


网站公告

今日签到

点亮在社区的每一天
去签到