如何获得确切的typeof是object / array / null ..?

时间:2012-11-20 04:54:28

标签: javascript jquery arrays object

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,什么都不是"object, array,null" - 实现这个目标的最佳方式是什么?

4 个答案:

答案 0 :(得分:3)

如果您使用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"作为其类型。

答案 1 :(得分:2)

您可以尝试提取构造函数名称,而不需要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

答案 2 :(得分: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 :(得分:1)

即使这太好了!

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';