Summary Notes for determining JavaScript data types, javascript Data Types

Source: Internet
Author: User
Tags iterable

Summary Notes for determining JavaScript data types, javascript Data Types

Use typeof to detect Data Types
Javascript comes with two types: Basic Data Types (undefined, string, null, boolean, function, object) and object type.

However, if you try to use typeof to detect all object types, "object" is returned and cannot be differentiated.

typeof null // "object"typeof []  // "object"typeof document.childNodes //"object"typeof /\d/ //"object"typeof new Number() //"object"

Use the constructor attribute to detect constructor types.

[]. Constructor === Array // truedocument. childNodes === NodeList // true/\ d /. constructor === RegExp // true function isRegExp (obj) {return obj & typeof obj = "object" & obj. constructor === RegExp;} // checks the regular expression object function isNull (obj) {return obj === null ;}

Construct detection can be used to complete most types of detection. If it is null, it can be compared directly. However, the array type in iframe cannot detect the correct type, which is a defect detected by construct. Meanwhile, DOM and BOM construct in earlier version IE cannot be accessed.

Use Object. prototype. toString to judge

Object.prototype.toString.call([]) //"[object Array]"Object.prototype.toString.call(/\d/) // "[object RegExp]"Object.prototype.toString.call(1)//"[object Number]"

Let's see.How to Use the toString method in jQuery source code

/** JQuery JavaScript Library v1.11.2 */var class2type = {}; // used to save the js data type jQuery. each ("Boolean Number String Function Array Date RegExp Object Error ". split (""), function (I, name) {// construct class2type to store Mappings of common types, traverse basic types, and assign values, the key value is [object type] class2type ["[object" + name + "]"] = name. toLowerCase () ;}); type: function (obj) {if (obj = null) {// if it is null, return the null String return obj + "";} // determine whether the specified parameter type is an object or Function. If yes, search for the toString key value name in the ing table and return it. If not, use typeof to obtain the correct type. Return typeof obj = "object" | typeof obj = "function "? Class2type [toString. call (obj)] | "object": typeof obj ;}, /****************************/jQuery. type (/\ d/) // "regexp" jQuery. type (new Number () // "number"

The toString method can be used to detect the problem because different objects will redefine their own toString methods.

Talk about some special types of Detection

The above debugging is carried out in IE8, because undefined is not a keyword in javascript, and can be assigned values under IE8 (later versions cannot be assigned values). View jQuery. the type source code shows that the undefined detection is completed by typeof undefined. JQuery. type does not check the correctness of undefined in the old IE. To obtain pure undefined, you can use void 0

In addition, for DOM, the value detected by the BOM object in the old IE using Objec. prototype. toString is "[Object object]".

However, the results in chrome are completely different (chrome can detect real types)

Learn about the special types of jQuery Detection

IsWindow: function (obj) {// ECMA specifies that window is the global Object global, and global. window === global return obj! = Null & obj = obj. window;}, isPlainObject: function (obj) {var key; if (! Obj | jQuery. type (obj )! = "Object" | obj. nodeType | jQuery. isWindow (obj) {return false;} try {// determine whether the latest prototype object contains the isPrototypeOf attribute if (obj. constructor &&! HasOwn. call (obj, "constructor ")&&! HasOwn. call (obj. constructor. prototype, "isPrototypeOf") {return false ;}} catch (e) {return false;} if (support. ownLast) {for (key in obj) {return hasOwn. call (obj, key );}}

Improvements in the mass Framework compared with jQuery

Var class2type = {// map all possible types to the class2type object to reduce the isXXX function "[object HTMLDocument]": "Document ", "[object HTMLCollection]": "NodeList", "[object StaticNodeList]": "NodeList", "[object DOMWindow]": "Window", "[object global]": "Window", "null": "Null", "NaN": "NaN", "undefined": "Undefined"}; type: function (obj, str) {var result = class2type [(obj = null | obj! = Obj )? Obj: serialize. call (obj)] | obj. nodeName | "#"; // serialize = class2type. toString if (result. charAt (0) = "#") {// compatible with legacy browsers and handle certain situations, such as Windows. opera // use IE678 window = document to be true, and document = window to be false. if (obj = obj.doc ument & obj.doc ument! = Obj) {// For DOM, BOM objects use nodeType (single) and item (node set) to judge result = "Window "; // returns the constructor name} else if (obj. nodeType = 9) {result = "Document"; // returns the constructor name} else if (obj. callee) {result = "Arguments"; // returns the constructor name} else if (isFinite (obj. length) & obj. item) {result = "NodeList"; // processing node set} else {result = serialize. call (obj ). slice (8,-1) ;}} if (str) {return str === result;} return result ;}

Class Array

Arrays of classes are a special type of data. They are similar to arrays but cannot use arrays. They have an obvious characteristic that they contain the length attribute, in addition, the key values are arranged in an integer order. Such an Array can be converted to a real Array using methods such as Array. slice () to use the method provided by Array.

Common class Arrays: arguments, document. forms, document. getElementsByClassName (and other column node sets NodeList, HTMLCollection), or some special objects, as shown below:

var arrayLike={    0:"a",    1:"b",    2:"c",    length:3 }

In general, Array. slice. call can be converted to an array of classes, but the old IE HTMLCollection, NodeList is not a subclass of the Object and cannot be used. In this case, an empty array needs to be constructed, then, push the traversal node as an empty array, and return the newly generated array. At the same time, we need to differentiate the window and string objects, because such objects also contain length> = 0 (length cannot be modified), but it is not a class array.

How does jQuery handle class Array

MakeArray: function (arr, results) {var ret = results | []; if (arr! = Null) {if (isArraylike (Object (arr) {jQuery. merge (ret, typeof arr = "string "? [Arr]: arr); // jQuery. merge merges the array. If it is a string, it is encapsulated into an array Riverside. Otherwise, it is merged in the world} else {push. call (ret, arr) ;}} return ret ;}

How does Ext. js handle class arrays?

ToArray: function (iterable, start, end) {if (! Iterable |! Iterable. length) {return []; // directly Returns []} if (typeof iterable = 'string') {iterable = iterable. split (''); // decomposition string} if (supportsSliceOnNodeList) {return slice. call (iterable, start | 0, end | iterable. length); // supported for NodeList} var array = [], I; start = start | 0; end = end? (End <0 )? Iterable. length + end: end): iterable. length; for (I = start; I <end; I ++) {array. push (iterable [I]);} return array ;}

How does mass Framework. js process class arrays?

Slice: W3C? Function (nodes, start, end) {// var W3C = DOC. dispatchEvent; IE9 began to support W3C event model return factorys. slice. call (nodes, start, end) ;}: function (nodes, start, end) {var ret = [], n = nodes. length; if (end = void 0 | typeof end = "number" & isFinite (end) {start = parseInt (start, 10) | 0; end = void 0? N: parseInt (end, 10); if (start <0) {start + = n;} if (end> n) {end = n;} if (end <0) {end + = n ;}for (var I = start; I <end; ++ I) {ret [I-start] = nodes [I] ;}} return ret;

The above is all the content of this article, hoping to help you learn

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.