zoukankan      html  css  js  c++  java
  • 怎样检测数据类型

    前言: 判断基本类型用: typeof, 判断引用类型用: instanceof

    注意:

    1. typeof可以当关键字使用, 也可以当函数使用, 它可以检测基本类型, 但无法检测引用类型.

    2. instanceof 只能作关键字使用, 可以检测引用类型, 不能检测基本类型.

    第一步: typeof 的使用方法

    typeof 1; // "number";
    typeof true; // "boolean";
    typeof "hello"; // "string";
    typeof []; // "object";
    typeof console; // "object";
    typeof {}; // "object"

    注意: 上面的代码告诉我们, typeof只能检测基本类型, 不能检测引用类型(全返回object);

    第二步: instanceof 的使用方法

    instanceof 可以检测引用类型, 其实际含义是: 检测某个实例是否是某个构造函数的实例

    console.log([] instanceof Array); // true;
    console.log({} instanceof Object); // true;
    console.log([] instanceof Object); // true;
    console.log(console.log instanceof Function); // true;
    console.log(console instanceof Object); // true;
    
    // instanceof 无法检测基本类型;
    1 instanceof Number; // fales;
    'hello' instanceof String; // false;
    true instanceof Boolean; // false

    注意: 

    1. 尽管一切皆对象, 但基本类型无法使用instanceof来检测;

    2. 数组的实例既是构造函数Array的实例, 也是Object的实例;

  • 相关阅读:
    第8章 字符串
    第7章 方法
    第6章 类和对象
    第5章 数组
    第4章 循环结构、break与continue
    第3章 选择结构
    第2章 变量、数据类型和运算符
    Codeforces Round #426 (Div. 2)
    CCNA学前基础一
    Tinkoff Challenge
  • 原文地址:https://www.cnblogs.com/aisowe/p/11634793.html
Copyright © 2011-2022 走看看