zoukankan      html  css  js  c++  java
  • 关于判断类型的方法

    老问题:关于判断类型的方法:

      1. typeof:这个很常用也很好用,缺点是当变量是对象时,这个方法无法精确区分到底是哪一种对象,比如 
    array,function,String,Number,Boolean都有可能:

    var a = new String("abc");
      var b = function(){};
      var c = [];
      alert(typeof a)    //object
      alert(typeof b)    //object
      alert(typeof c)    //object

       当然,如果你只需要区分基本数据类型还是可以的。

      2:instanceof: 这个方法是判断变量是否是某个构造对象的实例:  

      var c = [];
      alert(c instanceof Array)    //true

       当然通过constructor也可以判断,读者可以自己尝试。

      3:利用Object.prototype.toString;  

    function get_type (obj) {
    return obj === null ? 'null' : (obj === undefined ? 'undefined' : Object.prototype.toString.call(obj).slice(8, -  
    1).toLowerCase()); //返回这样的字符 截取后获得类型[object Array]
  • 相关阅读:
    164.Maximum Gap
    163.Missing Ranges
    162.Find Peak Element
    161.One Edit Distance
    160.Intersection of Two Linked Lists
    7.5爬取猫眼Top100电影名单
    7.5文件操作
    7.4文件操作(1)
    7.4一个失败的网易云爬虫,
    7.3数据结构(1)
  • 原文地址:https://www.cnblogs.com/taoze/p/2624395.html
Copyright © 2011-2022 走看看