zoukankan      html  css  js  c++  java
  • JavaScript typeof obj === ‘object’ 这样写有什么问题

    typeof Array, Object, new Class() 都会返回'object', 所以使用typeof不能准确的判断变量是否为object

    typeof [];  //object
    typeof {};  //object
    typeof new (function (){});  //object
    typeof 1//number
    typeof '1'//string
    typeof null//object
    typeof true//boolean
     
     要准确判断一个变量是否是一个对象,可以使用constructor以及instanceof判断。
    1. constructor是指该对象的构造函数, 使用constructor时, 要注意, 实例化类时, 类的prototype.constructor需要正确引用。
    ({}).constructor === Object;  //true
    (1).constructor === Number;  //true
    ([]).constructor === Array;  //true
    ('1').constructor === String;  //true
    (true).constructor === Boolean;  //true
    2. instanceof是指该对象是否为指定类的实例
    ({}) instanceof Object;  //true
    ([]) instanceof Array;   //true
    (1) instanceof Number;  //true
    ('1') instanceof String;  //true
    (true) instanceof Boolean;  //true
  • 相关阅读:
    文件操作-图片的拷贝
    UIBarbuttonItem
    pod 'Masonry' 自动布局
    文件操作——图片保存到本地
    IOS简单的定位
    UITapGestureRecognizer+动画
    KVO
    UIScrollView
    UITextField的使用
    1228.1——计算器(未使用MVC设计模式)
  • 原文地址:https://www.cnblogs.com/facial/p/5797629.html
Copyright © 2011-2022 走看看