zoukankan      html  css  js  c++  java
  • 关于JavaScript中的typeof与instanceof

    JavaScript中typeofinstanceof可以用来判断一个数据的类型,什么时候选择使用typeof?什么时候选择使用instanceof?

    typeof运算符

    typeof运算符返回值有以下几种

    • 原始数据类型
    typeof 123 // "number"
    typeof '123' // "string"
    typeof false // "boolean"
    
    • 函数类型
    function f() {}
    typeof f
    // "function"
    
    • undefined
    typeof undefined
    // "undefined"
    var x
    typeof x
    // "undefined
    
    • Object
    typeof window // "object"
    typeof {} // "object"
    typeof [] // "object"
    typeof null // "object
    

    instanceof运算符

    instanceof是判断变量是否为某个对象的实例,返回值为true或false。

    var o = {};
    var a = [];
    
    o instanceof Array // false
    a instanceof Array // true
    a instanceof Object // true
    

    typeof 对数组 [] 和对象 {} 的返回值都是Object,无法区分数组和对象,但是instanceof可以区分。

    对于什么时候该使用typeofinstanceof

    • 当变量可能为undefined的时候使用typeof运算符
    alert(typeof undefinedVariable); // alerts the string "undefined"
    alert(undefinedVariable instanceof Object); // throws an exception
    
    • 当变量可能为null的时候使用instanceof运算符
    var myNullVar = null;
    alert(typeof myNullVar ); // alerts the string "object"
    alert(myNullVar  instanceof Object); // alerts "false"
    

    link:
    https://stackoverflow.com/questions/899574/what-is-the-difference-between-typeof-and-instanceof-and-when-should-one-be-used

    https://www.jianshu.com/p/1216b1f429fb

  • 相关阅读:
    微信消息类型和事件类型
    lnmp环境搭建脚本
    laravel框架踩过的坑
    vue结构详解
    PHP消息队列实现及应用
    laravel 运行错误
    笔记分享
    cf730e
    cf 730i
    cf 731f
  • 原文地址:https://www.cnblogs.com/yuanchao-blog/p/JavaScript.html
Copyright © 2011-2022 走看看