【问题标题】:How to get exactly typeof is object/array/null..?如何准确地获取 typeof 是 object/array/null..?
【发布时间】:2012-11-20 04:54:28
【问题描述】:
var obj = {},ar = [],nothing=null,empty=undefined,word ='string',headorTail = true;

console.log(typeof obj) //object
console.log(typeof ar)//object
console.log(typeof nothing)//object
console.log(typeof empty)//undefined
console.log(typeof word)//string
console.log(typeof headorTail)//boolean

但是我怎样才能得到 obj,ar,nothing 的类型 "object, array,null" - 实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: javascript jquery arrays object


    【解决方案1】:

    如果你使用jQuery,你可以使用jQuery.type:

    jQuery.type(true) === "boolean"
    jQuery.type(3) === "number"
    jQuery.type("test") === "string"
    jQuery.type(function(){}) === "function"
    jQuery.type([]) === "array"
    jQuery.type(new Date()) === "date"
    jQuery.type(/test/) === "regexp"
    

    其他所有内容都返回 "object" 作为其类型。

    【讨论】:

      【解决方案2】:
      function getType(obj) {
          // Object.toString returns something like "[object Type]"
          var objectName = Object.prototype.toString.call(obj);
          // Match the "Type" part in the first capture group
          var match = /\[object (\w+)\]/.exec(objectName);
      
          return match[1].toLowerCase();
      }
      
      // Test it!
      var arr = [null, undefined, {}, [], 42, "abc"];
      arr.forEach(function(e){ console.log(getType(e)); });
      

      请参阅 MDN 上的 Object.toString

      【讨论】:

        【解决方案3】:

        可以尝试提取构造函数名,不需要JQuery:

        function safeConstructorGet(obj) {
          try {
            console.log(obj.constructor.name) //object        
          } catch (e) {
            console.log(obj)
          }
        }
        
        safeConstructorGet(obj); //Object
        safeConstructorGet(ar);  //Array
        safeConstructorGet(nothing);  //null
        safeConstructorGet(empty);  //undefined
        safeConstructorGet(word);  //String
        safeConstructorGet(headorTail); //Boolean
        

        【讨论】:

          【解决方案4】:

          这也太好了!

          function getType(v) {
              return (v === null) ? 'null' : (v instanceof Array) ? 'array' : typeof v;
          }
          
          var myArr = [1,2,3];
          var myNull = null;
          var myUndefined;
          var myBool = false;
          var myObj = {};
          var myNum = 0;
          var myStr = 'hi';
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-02-12
            • 2018-12-20
            • 1970-01-01
            • 1970-01-01
            • 2018-12-13
            • 2016-05-04
            • 2012-03-25
            • 1970-01-01
            相关资源
            最近更新 更多