宇阳 一直对网站开发领域很感兴趣,从小就希望有一个属于自己的网站,在17年时候成功进入站长圈,并通过各种自学,以及各种折腾,才有了你现在看到的这个网站
歌曲封面 未知作品

网站已运行 5 年 70 天 10 小时 10 分

Powered by Typecho & Sunny

2 online · 56 ms

Title

Object.prototype.toString.call()

宇阳

·

Article
⚠️ 本文最后更新于2022年06月24日,已经过了643天没有更新,若内容或图片失效,请留言反馈

Object.prototype.toString.call()

为什么要使用 Object.prototype.toString.call()

传统情况下我们需要判断一个变量的数据类型会使用 typeof 进行判断。但是typeof判断有局限性,因为它只能判断 NumberStringUndefinedBooleanObject 这五种数据类型。对于数组、对象以及null来说使用 typeof 都会统一返回为 Object。它只能判断基本数据类型。

♾️ javascript 代码:
        let n1;
        let n2 = 123;
        let n3 = '我是字符串';
        let n4 = [];
        let n5 = {};
        let n6 = null;
        let n7 = function(){};

        console.log(typeof n1); //undefined
        console.log(typeof n2); //number
        console.log(typeof n3); //string
        console.log(typeof n4); //object
        console.log(typeof n5); //object
        console.log(typeof n6); //object
        console.log(typeof n7); //function

所以我们就需要使用 Object.prototype.toString.call() 进行判断

♾️ javascript 代码:
 // 使用Object.prototype.toString.call()来判断数据类型
        let judge1 = Object.prototype.toString.call(); //[object Undefined]
        let judge2 = Object.prototype.toString.call(123); //[object Number]
        let judge3 = Object.prototype.toString.call('我是字符串'); //[object String]
        let judge4 = Object.prototype.toString.call([]); //[object Array]
        let judge5 = Object.prototype.toString.call({}); //[object Object]
        let judge6 = Object.prototype.toString.call(function () ☑️); //[object Function]
        let judge7 = Object.prototype.toString.call(null); //[object Null]

举个栗子
判断n的值是什么数据类型

♾️ javascript 代码:
       let n = function () ☑️
       if (Object.prototype.toString.call(n) === '[object String]') {
           console.log(n + ': 他是个字符串');
       } else if (Object.prototype.toString.call(n) === '[object Array]') {
           console.log(n + ': 他是个数组');
       } else if (Object.prototype.toString.call(n) === '[object Function]') {
           console.log(n + ': 他是个函数'); //输出这个
       } else if (Object.prototype.toString.call(n) === '[object Object]') {
           console.log(n + ': 他是个对象');
       }
现在已有 0 条评论,0 人点赞
Comment
发表
搜 索 消 息 足 迹
你还不曾留言过..
你还不曾留下足迹..
博主