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

    1、typeof:返回字符串,内容为所给值的类型。用于查询值类型

    console.log(typeof "abc")   —— string
    console.log(typeof 34)   —— number
    console.log(typeof true)   —— boolean
    var g;
    console.log(typeof g)   ——  undefined
    console.log(typeof undefined)  —— undefined
    console.log(typeof function add() {})   —— function

    当参数是一个函数时:
    function add(fn){
        var a = 1;
        if(typeof fn !="function"){
            throw new Error("arguments is a function")
        }
        fn(a)
    }
    add("a")   // Uncaught Error: arguments is a function

    2、toString当typeof返回字符串是"object"时,通过Object.prototype.toString.apply()

    console.log(typeof null)  —— object

    console.log(typeof [ ])   —— object

    console.log(Object.prototype.toString.apply(null));  —— [object Null]

    console.log(Object.prototype.toString.apply([ ]));   —— [object Array]

    function isArray(val) {
       return Object.prototype.toString.apply(val) === "[object Array]";
    }

    3、=== 与 == , !== 与  != 

    4、instanceof 判断对象构造函数类型

    function Dog () {}
    function Car() {}
    var g = new Dog();
    var c = new Car();
    console.log(g instanceof Dog);  // true
    console.log(c instanceof Car);   // true
  • 相关阅读:
    今天晚上有个什么样的博文呢
    STM8CubeMx来了
    开博啦
    Authentication
    文件上传设计要点
    分布式杂记
    SQL Server 知识集
    C# 集合使用误区
    网络知识集
    关于 elasticsearch 近实时特征的思考
  • 原文地址:https://www.cnblogs.com/yuyedaocao/p/12033504.html
Copyright © 2011-2022 走看看