Summary of four methods of judging data type by js and jquery
- 2021-08-09 06:47:17
- OfStack
1.typeof
typeof is an operator, which is used in two ways: typeof (expression) and typeof variable name, the first is to operate on expression, and the second is to operate on variable.
The results returned by this method are as follows:
Number, String, undefined, Bollean, Object, Function
The drawback is that if the data type is a reference data type, it can only return Object
console.log(typeof 1); //number
console.log(typeof true); //bollean
console.log(typeof ' Joy '); //string
console.log(typeof {}); //object
console.log(typeof []); //object
2.toString.call()
console.log(toString.call(666)); //[object Number]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call(' Joy ')); //[object String]
console.log(toString.call(undefined)); //[object Undefined]
console.log(toString.call({})); //[object Object]
console.log(toString.call([])); //[object Array]
console.log(toString.call(function(){})); //[object Function]
3.instanceof
In JavaScript, the typeof operator will be used to judge the type of a variable. When using typeof operator, there will be a problem when using reference type to store values. No matter what type of object is referenced, it will return "object". ECMAScript introduces another Java operator, instanceof, to solve this problem. The instanceof operator is similar to the typeof operator and is used to identify the type of object being processed. Unlike the typeof method, the instanceof method requires the developer to explicitly confirm that the object is of a specific type.
A instanceof B can judge whether A is an instance of B, return a Boolean value, and judge the data type by the construction type
console.log(arr instanceof Array ); // true
console.log(date instanceof Date ); // true
console.log(fn instanceof Function ); // true
4. Judging from the contructor of the object
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true
Method for judging data type in JQuery
Returns 1 Boolean value
jQuery Object .isArray(); // Determine whether it is an array
jQuery Object .isEmptyObject(); // Determine whether it is an empty object
jQuery Object .isFunction(): // Determine whether it is a function
jQuery Object .isNumberic(): // Determine whether it is a number
jQuery Object .isWindow(): // Determine whether it is window Object
jQuery Object .isXMLDoc(): // Judgment judgment 1 A DOM Whether the node is in the XML In the document
Summarize