Summary of the JS data type determination (very comprehensive)

Source: Internet
Author: User
Tags iterable

Using typeof to detect data types

JavaScript comes with two sets of types: basic data Type (Undefined,string,null,boolean,function,object) and object type.

However, if you try to use TypeOf to detect that the object type is returned "object", it cannot be distinguished

typeof NULL  // "Object" typeof []    //  "Object"typeof Document.childnodes  //"Object" typeof /\d/  //"Object"typeofnew//" Object "

To detect a type's constructor with the constructor property
 [].constructor = = = Array // true  Document.childnodes = = = NodeList // true  /\d/.constructor = = = RegExp // true  function   Isregexp (obj) { return  obj && typeof  obj = = = "Object" && obj.constructor === RegExp;}  //  detect Regular Expression object  function   IsNull (obj) { return  obj = = = null  ;}  

Most type detection can be done with construct detection, and NULL is a special direct comparison. However, the array type in the IFRAME does not detect the correct type, which is a flaw detected with construct, and the construct of the DOM and BOM in the old version of IE is inaccessible.

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]"

Look at how the ToString method is used in the jquery source code

/** jQuery JavaScript Library v1.11.2*/varClass2type = {};//used to save JS data typeJquery.each ("Boolean number String Function Array Date RegExp Object Error". Split (""),function(I, name) {//constructs class2type to store common types of mappings, traverse base types and assign values to [object type]class2type["[Object" + name + "]"] =name.tolowercase ();}); Type:function(obj) {if(obj = =NULL) {//returns the null string first if it is null                        returnobj + ""; }//then determine whether the given parameter type is an object or function, and if so, look for the name of the key value in the mapping table and return it, if not, use typeof to get the correct type.                 return typeofobj = = = "Object" | |typeofobj = = = "function"?class2type[Tostring.call (obj)]|| "Object" :                        typeofobj; },/****************************/Jquery.type (/\d/)//"RegExp"Jquery.type (NewNumber ())//"Number"

The ToString method can be used here to detect because different objects will redefine their tostring method

Talk about some special types of tests.

The above debugging is done in IE8, because undefined in JavaScript is not a keyword, under IE8 (after the version can not be assigned) is assignable, view Jquery.type source, for undefined detection by typeof Undefined completed. Jquery.type does not detect the correctness of undefined in the old ie. To get pure undefined you can use void 0

In addition, the values detected by the Dom,bom object in the old IE using Objec.prototype.toString are "[Object Object]"

But the results under Chrome are completely different (chrome can detect the real type)

Learn about the special types of jquery detection
IsWindow:function(obj) {//The ECMA specifies that window is global, and global.window = = = Globals                returnObj! =NULL&& obj = =Obj.window; }, Isplainobject:function(obj) {varkey; if(!obj | | jquery.type (OBJ)!== "Object" | | obj.nodetype | |Jquery.iswindow (obj)) {                        return false; }                Try{//determine if its most recent 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(Keyinchobj) {                                returnhasown.call (obj, key); }                }

Mass framework relative to jquery in the area of improvement
varClass2type = {//The possible types are mapped in the Class2type object, thereby reducing 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) {varresult = class2type[(obj = =NULL|| obj!== obj)? Obj:serialize.call (obj)] | | Obj.nodename | | "#";//Serialize = = Class2type.tostring            if(Result.charat (0) = = = = "#") {//compatible with legacy browsers and handling individual cases, such as Window.opera                //using IE678 window = = Document for true,document = = window is a magical feature of false                if(obj = = Obj.document && obj.document! = obj) {//NodeType (single) and Item (node collection) are used to determine the Dom,bom objectresult = "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 Collections}Else{result= Serialize.call (obj). Slice (8,-1); }            }            if(str) {returnstr = =result; }            returnresult; }

Class Array

Class arrays are a special kind of data type, they are similar to array, but they can not use the method of array, they have an obvious feature is the length property, and the key value is ordered by integers. Such arrays can be converted to real arrays by means of array.slice (), thereby using the method provided by array.

Common class Arrays: Arguments,document.forms,document.getelementsbyclassname (such as some column node collection nodelist,htmlcollection), or some special objects, As shown below:

var arraylike={       0: "A",       1: "B",       2: "C",       Length:3   }  

Typically, you can convert an array of classes through Array.slice.call, but the old IE's htmlcollection,nodelist is not a subclass of object, and you cannot use this method, you need to construct an empty array, and then traverse the node push as an empty array, returning the newly generated array You can also distinguish between window and string objects, because objects of this class also contain length>=0 (length cannot be modified), but are not class arrays.

How jquery handles arrays of classes
Makearray:function(arr, results) {varret = Results | | []; if(Arr! =NULL ) {                        if(Isarraylike (Object (arr))) {Jquery.merge (ret), typeofarr = = = "string"?[arr]: arr); //jquery.merge Merge arrays, if strings are encapsulated as a group of Riverside, not the world merges}Else{push.call (ret, arr); }                }                returnret; }

How Ext.js handles array of classes
ToArray:function(iterable, start, end) {if(!iterable | |!iterable.length) {return[];//non-class array type returns directly []                }                if(typeofiterable = = = ' String ') {iterable= Iterable.split (");//Explode string                }                if(supportssliceonnodelist) {returnSlice.call (iterable, start | | 0, END | | iterable.length);//for nodelist Support                }                varArray =[], I; Start= Start | | 0; End= end? (End < 0)? Iterable.length +end:end): iterable.length;  for(i = start; i < end; i++) {Array.push (iterable[i]); }                returnArray; }

Mass framework.js is how to handle array of classes
SLICE:W3C?function(nodes, start, end) {//var = doc.dispatchevent; IE9 began to support the event model            returnFactorys.slice.call (nodes, start, end); } : function(nodes, start, end) {varRET =[], n=nodes.length; if(End = =void0 | |typeofend = = = "Number" &&isfinite (end)) {Start= parseint (Start, 10) | | 0; End= End = =void0? N:parseint (end, 10); if(Start < 0) {Start+=N; }                if(End >N) {end=N; }                if(End < 0) {End+=N; }                 for(vari = start; I < end; ++i) {ret[i-Start] =Nodes[i]; }            }            returnret; }

Summary of the JS data type determination (very comprehensive)

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.