zoukankan      html  css  js  c++  java
  • 判断数据类型

    Object.prototype.toString.call(123).slice(8, -1) // Number
    
    
    // 直接输出数类型 首字母大写 Number、Array、Function等

    下面是各种数据类型调用toString()方法的返回值

    数据类型例子return
    字符串 “foo”.toString() “foo”
    数字 1.toString() Uncaught SyntaxError: Invalid or unexpected token
    布尔值 false.toString() “false”
    undefined undefined.toString() Uncaught TypeError: Cannot read property ‘toString’ of undefined
    null null.toString() Uncaught TypeError: Cannot read property ‘toString’ of null
    String String.toString() “function String() { [native code] }”
    Number Number.toString() “function Number() { [native code] }”
    Boolean Boolean.toString() “function Boolean() { [native code] }”
    Array Array.toString() “function Array() { [native code] }”
    Function Function.toString() “function Function() { [native code] }”
    Date Date.toString() “function Date() { [native code] }”
    RegExp RegExp.toString() “function RegExp() { [native code] }”
    Error Error.toString() “function Error() { [native code] }”
    Promise Promise.toString() “function Promise() { [native code] }”
    Obejct Object.toString() “function Object() { [native code] }”
    Math Math.toString() “[object Math]”

    所有类在继承Object的时候,改写了toString()方法。 Object原型上的方法是可以输出数据类型的。因此我们想判断数据类型时,也只能使用原始方法。

    继而可使用这个方法去判断数据类型:

    Object.prototype.toString.call(obj)

  • 相关阅读:
    抽象类与抽象方法
    简单工厂模式
    面向对象的七种基本设计原则
    HashTable集合遍历的三种方法
    继承(父类为虚方法以及子类的重写)
    继承(is与as)
    Chrome OS 更新新版本可让Linux访问USB连接的Android设备
    谷歌对Intel 10nm进度不满
    盖茨对没能做好手机系统对抗苹果表示遗憾
    微软内部封杀 Slack
  • 原文地址:https://www.cnblogs.com/memphis-f/p/14085109.html
Copyright © 2011-2022 走看看