• javascript疑难问题---19、获取变量的类型


    javascript疑难问题---19、获取变量的类型

    一、总结

    一句话总结:

    获取变量的类型我们主要是通过 调用对象的原型上的toString方法,例如 Object.prototype.toString.call(a).slice(8,-1);
    function type_name(a) {
      return Object.prototype.toString.call(a).slice(8,-1);
    }
    console.log(type_name(''));//String
    console.log(type_name([]));//Array
    console.log(type_name({}));//Object

    二、获取变量的类型

    博客对应课程的视频位置:19、获取变量的类型
    https://www.fanrenyi.com/video/4/214

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>获取变量的类型</title>
     6 </head>
     7 <body>
     8 <!--
     9 
    10 获取变量的类型我们主要是通过 调用对象的原型上的toString方法
    11 
    12 
    13 -->
    14 <script>
    15 
    16     //需求,写一个函数,传进来各种类型的变量,返回这个变量对应的类型的字符串
    17     //比如说传进去数组,返回Array
    18     //比如说传进去对象,返回Object
    19     //比如说传进去null,返回Null
    20     //等等
    21 
    22     // console.log({});
    23     // console.log({}.toString());
    24     //
    25     // console.log([]);
    26     // console.log([1,2].toString());
    27     //
    28     // Object.prototype.toString();
    29     // Object.prototype.toString.call([]);
    30     // console.log(Object.prototype.toString.call([]));
    31     //
    32     // console.log(Object.prototype.toString.call(''));
    33     // console.log(Object.prototype.toString.call(null));
    34     // console.log(Object.prototype.toString.call(undefined));
    35     // console.log(Object.prototype.toString.call(true));
    36     //
    37     // console.log(Object.prototype.toString.call(true).slice(8,-1));
    38     // console.log(Object.prototype.toString.call('11').slice(8,-1));
    39 
    40     function type_name(a) {
    41         return Object.prototype.toString.call(a).slice(8,-1);
    42     }
    43 
    44     console.log(type_name([]));
    45     console.log(type_name({}));
    46 
    47 </script>
    48 </body>
    49 </html>
     
  • 相关阅读:
    苹果 iOS 8 新固件新功能特性总结汇总 (苹果 iPhone/iPad 最新移动操作系统)
    为什么魔兽世界里男性玩家爱选女性角色?
    腾讯PK微软 王者之战一触即发
    策略模式
    代理模式
    模板模式
    适配器模式
    工厂模式
    随机森林步骤(转)
    马氏距离通俗理解(转)
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12827733.html
Copyright © 2020-2023  润新知