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)

  • 相关阅读:
    B-Tree(B树)原理及C++代码实现
    Select(快速选择顺序统计量)原理及C++代码实现
    BucketSort(桶排序)原理及C++代码实现
    RadixSort(基数排序)原理及C++代码实现
    CountingSort(计数排序)原理及C++代码实现
    面向对象之封装
    今日算法题
    面向对象之抽象类和接口
    面向对象之多态
    今日算法题
  • 原文地址:https://www.cnblogs.com/memphis-f/p/14085109.html
Copyright © 2011-2022 走看看