JavaScript data Type Decision Summary Notes _ Basics

Source: Internet
Author: User
Tags arrays iterable split

Using typeof to detect data types
JavaScript is self-contained with two sets of types: basic data Types (Undefined,string,null,boolean,function,object) and object types.

But if you try to use TypeOf to detect an object type, you can always return "object" without distinction.

typeof null//"Object"
typeof []  //"Object"
typeof Document.childnodes//"Object"
typeof/\d///" Object "
typeof new Number ()//" 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;
} Detection of 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 by construct, while the DOM and BOM construct are inaccessible in older versions of IE

Using 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
*
/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 stores common types of mapping relationships, traversing base types and assigning values to [object type]
 class2type[' [object ' + name + '] '] = Name.tolowercase (); 
   
    });
Type:function (obj) {
  if (obj = = null) {//First returns null string return
   obj + "";
  }
Then to determine whether the given parameter type is an object or function, it is possible to find the name of the key value after ToString in the mapping table and return it, if not, use typeof to get 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"
   

This can be detected using the ToString method because different objects will redefine their tostring method

Tell me about some special types of tests.

The above debugging is done in IE8, because undefined in JavaScript is not a keyword, in IE8 below (after the version can not assign value) is can be assigned, see Jquery.type Source code, for undefined detection by IS typeof Undefined completed. Jquery.type is not able to detect the correctness of undefined in old ie. To get pure undefined, you can use void 0

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

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

Learn about the special types of jquery detection

Iswindow:function (obj) {//ECMA stipulates that window is global and Global.window = = global return
 obj!= null && obj = = OB J.window
},
isplainobject:function (obj) {
 var key;
 if (!obj | | jquery.type (OBJ)!== "Object" | | obj.nodetype | | jquery.iswindow (obj)) {return
  false;
 }
 try {//judge whether 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) C15/>return false;
 if (support.ownlast) {
  for [key in obj] {return
   hasown.call (obj, key);
  }
 }

Where the mass framework is improving relative to jquery

var class2type = {//The possible types are mapped to the Class2type object, thereby reducing the ISXXX function "[Object HTMLDocument]": "Document", "[Object Htmlcollecti On]: "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.nod ename | | "#"; Serialize = = Class2type.tostring if (result.charat (0) = = "#") {//compatible with older browsers and handling individual cases, such as Window.opera//using IE678 window = = Document for true,document = = window unexpectedly false Magic attribute if (obj = = obj.document && obj.document!= obj) {//Pair Dom,bom Object Using NodeType (single) and item (node set) to Judge result = "window"; Return constructor Name} else if (Obj.nodetype = 9) {result = ' Document ';//return constructor name} else if (Obj.callee) {Resul t = "Arguments"; Return constructor Name} else if (Isfinite (obj.length) && obj.item) {result = ' nodelist ';//Process node collection} else {
     result = Serialize.call (obj). Slice (8,-1);
   } if (str) {return str = = result;
  return result; }

Class Array

An array of classes is a special type of data that exists, they are similar to arrays but cannot use array, and they have an obvious feature of the length attribute, and the key values are arranged in an orderly order. Such an array can be converted to a real array by means of array.slice (), thereby using the method provided by the array.

Common class Arrays: Arguments,document.forms,document.getelementsbyclassname (such as some column node sets 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 htmlcollection,nodelist is not a subclass of object and cannot be used, and you need to build an empty array. Then the traversal node push, like an empty array, returns the newly generated array, distinguishing between window and string objects, since such objects also contain length>=0 (length cannot be modified), but are not class arrays.

How jquery handles array of classes

Makearray:function (arr, results) {
 var ret = Results | | [];
 if (arr!= null) {
  if (Isarraylike (arr)) {
   Jquery.merge (ret,
    typeof arr = = "string"?
    ) [arr]: arr
   );  Jquery.merge merge arrays, if strings encapsulate a few groups of Riverside, not the world merging
  } else {
   push.call (ret, arr);
  }
 return ret;
}

Ext.js is how to handle an array of classes

Toarray:function (iterable, start, end) {
    if (!iterable | | |!iterable.length) {return
     [];  Non-class array types are returned directly []
    }
    if (typeof iterable = = = ' String ') {
     iterable = Iterable.split (');  Explode string
    }
    if (supportssliceonnodelist) {return
     Slice.call (iterable, start | | 0, END | | iterable.length); /For nodelist support
    }
    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;
   }

Mass framework.js is how to handle an array of classes

SLICE:W3C? function (nodes, start, end) {//var) = doc.dispatchevent; IE9 begins to support the event model of the
 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) | | 0;
  End = end = = void 0? N:parseint (end, ten);
  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 the entire content of this article, I hope to help you learn

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.