Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get exactly typeof is object/array/null..?

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

But how can i get the type of obj,ar,nothing as "object, array,null" - what is the best way to achieve this?

like image 715
3gwebtrain Avatar asked Nov 20 '12 04:11

3gwebtrain


4 Answers

If you use jQuery, you can use 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"

Everything else returns "object" as its type.

like image 119
Pragnesh Chauhan Avatar answered Oct 13 '22 00:10

Pragnesh Chauhan


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)); });

See the Object.toString on MDN.

like image 39
Reuben Morais Avatar answered Oct 13 '22 00:10

Reuben Morais


You can try to extract constructor name, and you don't need 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
like image 41
Damask Avatar answered Oct 13 '22 00:10

Damask


Even this too good!

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';
like image 37
3gwebtrain Avatar answered Oct 13 '22 01:10

3gwebtrain