Usually we use the typeof operator to determine the type of the variable in order to be fast, but this does not accurately determine the type of the variable.
Like what:
typeof []; // Return ' object ' typeof {}; // Return ' object ' typeof new Number (1); // Return ' object ' typeof new Array (' A ', ' B '); // typeof New string (' abc '); //returns ' object '
typeof new Function (); //returns ' function '
The typeof operator usually returns ' object ' In addition to the new Function when judging new objects.
So to be able to determine the exact type, we found a better way to get the concrete type of the variable by calling the ToString method on the Object prototype.
Object.prototype.toString. Pager (obj);
I looked at the type function in jquery that was used to judge variable types, which was relatively complex to implement.
Its usage is similar to this:
var abc = ' abc '; if (Jquery.type (ABC) = = = ' String ' ) { //is a character type, then execute here }else{ // Not just do it here }
The Jquery.type function eventually returns the type of the variable passed in, and it needs to be judged by the operator comparison.
Feel a little superfluous, not as easy as the following:
var abc = ' abc '; if (Istype (ABC, ' string ')) { //true}else{ // False}
The Istype function takes a string argument and returns True or false directly.
That's how I realized it:
function istype (obj, type) { var tostr = Object.prototype.toString; var toLower = tostr.call (obj). toLowerCase (); return tolower.indexof (' [object ' + Type + '] ')!==-1;}
There is also a version that is implemented by the regular:
function istype (obj, type) { var tostr = Object.prototype.toString.call (obj); return (new RegExp (' \\[object ' + type + ' \ \] ', "I")). Test (TOSTR);}
In JavaScript, the type judgment is very common, so I add this function directly to the object.prototype, so that each variable can inherit the function.
function (type) { var tostr = Object.prototype.toString; var This ). toLowerCase (); return tolower.indexof (' [object ' + Type + '] ')!==-1;};
This adds a lot of convenience to the words:
' abc '. Istype (' string ')//returns True' abc '. Istype (' number ')//returns false[' A ', ' B ', ' C '].istype (' array ')//returns True[' A ', ' B ', ' C '].istype (' string ')//returns false(123). Istype (' number ')//returns True(123). Istype (' string ')//returns falseNewDate (). Istype (' Date ')//returns TrueNewDate (). Istype (' number ')//returns false
JavaScript type judgment