zoukankan      html  css  js  c++  java
  • javascript数组、对象和Null的typeof同为object,区分解决办法

    在JS里typeof 大家用的很多,可以使对于数组、对象和Null无法区分的问题,看了看犀牛书还是有解决办法的。

    document.writeln(typeof "abc"); //string
    document.writeln(typeof 123);   //number
    document.writeln(typeof true);  //boolean
    document.writeln(typeof eval);  //function
    document.writeln(typeof []);    //object
    document.writeln(typeof null);  //object
    document.writeln(typeof {});    //object

    基本数据类型基本都出来了,可是数组、对象和null没办法区分的。我们看看怎么破。

    其实在哪里听过这么一句话,JavaScript 中一切都是对象,现在我也有所体会,看看往下看。

    Object.prototype.toString.call() 
    //ECMA 5.1 中关于该方法的描述
    //[object Undefined] 这个是打印出来的结果

    这个该怎么用呢?直接上例子

    Object.prototype.toString.call([]) == "[object Array]"
    Object.prototype.toString.call({}) == "[object Object]"
    Object.prototype.toString.call(null) == "[object Null]"

    以上就清晰明了的区分了它们,JavaScript 中一切都是对象就完全体现在这里了,我们试试基础数据类型。

    Object.prototype.toString.call(123) == "[object Number]"
    Object.prototype.toString.call("arr") == "[object String]"
    Object.prototype.toString.call(true) == "[object Boolean]"

    看结果应该都是true,应该就是这么证明吧,问题解决了。其实还是有其他方法也能区分直接上代码,大家私下试试吧。

    (typeof arr == "object") && (arr.constructor == Array)
    (typeof arr == "object") && (arr instanceof Array)
  • 相关阅读:
    Dubbo (开源分布式服务框架)
    Springboot+Jpa的使用
    springboot(十二):springboot如何测试打包部署
    Java NIO:IO与NIO的区别
    eclipse下搭建shell脚本编辑器--安装开发shell的eclipse插件shelled
    spring boot
    【微服务架构】SpringCloud组件和概念介绍
    java正则表达式
    java的反射机制原理
    nginx代理服务器
  • 原文地址:https://www.cnblogs.com/gada/p/3277659.html
Copyright © 2011-2022 走看看