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

  • 相关阅读:
    IDEA调试快捷键
    视频预览
    文件上传:简单的demo
    Java 运行时优化
    Java 类加载
    Java StringTable
    Java 为什么不用Vector
    C++ 查找函数
    JVM 垃圾回收
    JVM 直接内存
  • 原文地址:https://www.cnblogs.com/yuanchao-blog/p/JavaScript.html
Copyright © 2011-2022 走看看