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

    5种基本数据类型:Undefined、Null、Boolean、Number和String。
    1中复杂数据类型:Object

    使用typeof检测

    typeof操作符返回一个字符串,表示未经求值的操作数的类型。

    typeof可能的返回值:

    • "undefined"——如果这个值未定义;

    • "boolean"——如果这个值是布尔值;

    • "string"——如果这个值是字符串;

    • "number"——如果这个值是数值;

    • "object"——如果这个值是对象或 null;

    • "function"——如果这个值是函数。

    注意事项:
    typeof null 返回 object。
    typeof 是一个操作符而不是函数,圆括号尽管可以使用,但不是必需的。
    //typeof str 或者 typeof(str) 均可以

    使用instanceof检测

    用来检测引用类型:知道一个值是什么类型的对象。返回true/false。

    所有引用类型的值都是 Object 的实例。

    • 如果使用 instanceof 操作符检测基本类型的值,则该操作符始终会返回 false,因为基本类型不是对象。但是使用new关键字构造基本数据的包装对象的实例时instanceof操作符也会返回true。(instanceof只适用于构造函数创建返回的复杂对象和实例。)

    • 用instanceof检测undefined和null是不是Object实例时,返回false。

        function Person(){}
        function Student(){}
        Student.prototype = new Person();
        var John = new Student();
        console.log(John instanceof Student); // true
        console.log(John instancdof Person);  // true
        console.log(John instancdof Object);  // true
        var a;
        
        
        用instanceof检测undefined和null是不是Object实例时,返回false。
        typeof a;    //"undefined"
        a instanceof Object;  //false
        var b = null;    
        typeof b;    //"object"
        b instanceof Object;    //false
    

    使用constructor检测

    本文转载于:猿2048js 数据类型检测

  • 相关阅读:
    StratifiedKFold和KFold的区别(几种常见的交叉验证)
    剑指offer:用栈来建立队列
    剑指offer:斐波那契数列
    树状数组 gcd 查询 Different GCD Subarray Query
    Loadrunner的使用
    Loadrunner的使用
    MySQL Windows 环境安装
    RobotFrameWork 自动化环境搭建(基于 python3.6)
    MySQL Linux 环境安装
    【读书笔记】状态模式代码C#
  • 原文地址:https://www.cnblogs.com/10manongit/p/12610403.html
Copyright © 2011-2022 走看看