zoukankan      html  css  js  c++  java
  • 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>
     
  • 相关阅读:
    vscode里的NPM脚本
    Vue之生命周期activated与created使用
    分享10个超棒的设计素材网站
    使用node搭建静态资源服务器
    vue 动态组件的传值
    一文带你入门正则表达式
    一文告诉你git如何使用
    一文告诉你三种常见跨域解决方案
    一文告诉你原型与原型链是什么?
    一文告诉你 Event Loop 是什么?
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12827733.html
Copyright © 2011-2022 走看看