This time I will bring you typeof and type judgment in JS (with code). What are the precautions for typeof and type judgment in JS? The following is a practical case. Let’s take a look. .
typeof
ECMAScript has 5 primitive types, namely Undefined, Null, Boolean, Number and String. We all know that you can use the typeofoperator to find the type of a variable, but when is used to reference a type variable, it will only return object, which means that typeof can only Correctly identify basic type value variables.
var a = "abc"; console.log(typeof a); // "string" var b = 123; console.log(typeof b); // "number" var c = true; console.log(typeof c); // "boolean" var d = null; console.log(typeof d); // "object" var f = undefined; console.log(typeof f); // "undefined" var g; console.log(typeof g); // "undefined" console.log(typeof x); // "undefined"
var a = function() { }; console.log(typeof a); // "function" var b = [1,2,3]; console.log(typeof b); // "object" var c = { }; console.log(typeof c); // "object"
Type judgment
Type judgment generally means judging whether it is an array or an empty object. This is the judgment method I have used or seen every day for this requirement Determine whether it is an array There is an array: 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 general, which is the abbreviation of Object.prototype.toString.call(a). The variables judged by instanceof and constructor must be declared on the current page. For example, a page (parent page) has a frame, and the frame refers to a page (child page). An a is declared in the child page and assigned a value. Give a variable to the parent page, then judge the variable, Array == object.constructor will return false;var a = [1,2,3,4,5]; console.log(toString.call(a)); // "[object Array]" console.log(a instanceof Array); //true console.log(a.constructor == Array); //true
method one:
JSON.stringify(obj); // "{}" is converted into a JSON object to determine whether it is an empty braceMethod Two:
if(obj.id){ //IfMethod three:
function isEmptyObject(e) { var t; for (t in e) return !1; return !0 } //trueisEmptyObject(obj); //falseisEmptyObject({ "a":1, "b":2});
The above is the detailed content of typeof and type judgment in JS (with code). For more information, please follow other related articles on the PHP Chinese website!