typeof
ECMAScript has 5 primitive types (primitive type), namely Undefined, Null, Boolean, number, and String. We all know that you can use the TypeOf operator to get the type of a variable, but the reference type variable only returns object
, meaning that typeof only correctly recognizes the base type value variable.
varA = "abc"; Console.log (typeofa);//"string"varb = 123; Console.log (typeofb);//"Number"varc =true; Console.log (typeofc);//"Boolean"varD =NULL; Console.log (typeofD);//"Object"varf =Undefined;console.log (typeoff);//"undefined"varG;console.log (typeofg);//"undefined"Console.log (typeofx);//"undefined"
You might ask why the TypeOf operator returns "Object" for a null value. This is actually an error in the initial implementation of JavaScript, and is then used by ECMAScript. Now NULL is considered a placeholder for the object, explaining the contradiction, but technically it is still the original value.
The last one is strange, typeof a non-existent variable x
actually returns "Object" instead of "undefined".
We are here to code:
var function () {};console.log (typeof// "function"var b = []; Console.log ( typeof// "Object"var c = {};console.log (typeof // "Object"
Returns "Object" for both arrays and objects, so a common requirement in our daily development is how to determine whether a variable is an array or an object.
Type judgment
Type judgment, which is generally the determination of whether an array is an empty object. This is a judgment method that I have used or seen in my daily life for this need.
Determines whether an array is
There are arrays:var a = [1,2,3,4,5];
Method One:
Tostring.call (a); "[Object Array]"
Method Two:
a instanceof Array; True
Method Three:
A.constructor = = Array; True
The first method is more generic, that Object.prototype.toString.call(a)
is, shorthand.
instanceof
and constructor
judged variables, must be declared on the current page, for example, a page (parent page) has a frame, the frame refers to a page (sub-page), in the Sub-page declaration of a, and assign it to a variable of the parent page, then the variable will be Array == object.constructor
returned false
;
var a = [1,2,3,4,5// "[Object Array]" instanceof// True//true
Determine if the object is empty
There are variables:var obj = {};
Method One:
Json.stringify (obj); // "{}"
To determine whether an empty curly brace is converted to a JSON object
Method Two:
if (obj.id) {//If the property ID exists ....}
This method compares the soil, most people can think, the premise is to know that there is a property in the object.
Method Three:
function Isemptyobject (e) {var t; for (T in E) return! 1; return!0}//trueisemptyobject (obj); Falseisemptyobject ({"A": 1, "B": 2});
This method is the implementation of the jquery Isemptyobject () method.
typeof and type judgments in JavaScript