• js 中使用typeof


    >typeof(null)
    <"object"

    对null执行typeof预算,结果返回字符串'object',也就是说,可以将null认为是一个特殊的对象值,含义是“非对象“。

    例如:用typeof obj ===‘object’判断obj是否是一个object

    写法一:

    var obj = {
      name: 'Mocen'
    }
        
    function output(obj) {
      if (typeof obj === 'object') {
        console.log(obj.name);
      } else {
        console.log('obj is not a object');
      }
    }
    output(obj);

    写法二:

    var obj = {
      name: 'xiaoming'
    }
    function output(obj) {
      if (!obj && typeof obj === 'object') {
        console.log(obj.name);
      } else {
        console.log('obj is not a object');
      }
    }
    output(obj);

    后者更为严谨

    typeof在检测到null时也会显示为object,但在javascript中null并非对象,因此需要增加一个检测null的模块:
    if (typeof obj === 'object' && obj !== null) ;


    作者:默成S
    链接:https://www.jianshu.com/p/a69b3bc9bdc2
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
  • 相关阅读:
    协成
    进程与线程-多线程
    进程与线程2
    进程与线程
    socket编程
    常用模块二(hashlib、configparser、logging)
    异常处理
    python之路——面向对象进阶
    封装
    初识——面向对象
  • 原文地址:https://www.cnblogs.com/liuw-flexi/p/11855970.html
Copyright © 2020-2023  润新知