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)
  • 相关阅读:
    线段树模板题 contest 线段树 T5
    Guide AHOI2017 洛谷P3720
    静态RMQ模板题 contest 静态RMQ T2
    树状数组模板题 P1904
    AC自动机模板题 P2017
    高精度排序模板题 P1110
    Trie树模板题 P2016
    树状数组套权值线段树
    爬山 启发式合并 / STL
    [POI2011]ROT-Tree Rotations 线段树合并|主席树 / 逆序对
  • 原文地址:https://www.cnblogs.com/gada/p/3277659.html
Copyright © 2011-2022 走看看