A better JavaScript typeof function
Often times during our JavaScript development we may need to know the type of an "object" in JavaScript, using the typeof functionality provided by JavaScript works sometimes and other times it might fail. Some examples are provided below.
typeof 2 : returns "number"
typeof "" : returns "string"
typeof function(){} : returns "function"
typeof /\d/ : returns "object" // fail !!! this is actually a regexp
I have a written a simple replacement function for typeof that pretty much returns the same results, but it's more robust and always returns the correct value
var itypeof = function (val) {
return Object.prototype.toString.call(val).replace(/(\[|object|\s|\])/g,"").toLowerCase()
}
itypeof(2) : returns "number"
itypeof ("") : returns "string"
itypeof (function(){}) : returns "function"
itypeof (/\d/) : returns "regexp"
ReplyDeletenice article.thank you for sharing useful post.
web programming tutorial
welookups