Several ways of detecting data types in JS and their advantages and disadvantages "turn"

Source: Internet
Author: User

Limitations:
1) typeof null, "Object"
2) The detection of either an array or a regular return is an "object", so typeof cannot determine whether a value is a numeric group

1 console.log(typeof[12, 23]);//->"Object"

2, Instanceof/constructor

Detects if an instance belongs to a class
Use Instanceof/constructor to detect arrays and regular

123456 console.log ([] < /code>instanceof  array); //->true console.log (/^$/  instanceof  regexp); //->true console.log ([]  instanceof  object); //->true  console.log ([]. constructor = = = Array); //->true console.log ([].constructor = = = Object); //->false

Constructor can avoid instanceof detection of arrays, using object is also a problem of true

1 console.log({}.constructor === Object);//true<br>console.log([].constructor === Object);//false

Limitations:

1) When using instanceof detection, as long as the current class on the prototype chain of the instance (can be found through the prototype chain __PROTO__), the detected results are true

12345 var  odiv = document.getElementById ( //htmldivelement->htmlelement->element->node->eventtarget-> Object console.log (odiv  instanceof  htmldivelement); //->true console.log (odiv  instanceof  node); //->true console.log (odiv  instanceof  object); //->true

2) The value of the base data type cannot be detected with instanceof

1 console.log(1 instanceofNumber);//->false

Two ways to create an array (object, regular, function ...)
For reference data types, the two methods we create are instances of the owning class, and all are values of the object data type, and there is no difference.

12 varary = [];var ary = newArray;

For basic data types, although either way is created as an instance of the owning class (methods defined on the prototype of the class can be used), the literal method creates the basic data type, and the instance creates the object data type.

123 varnum1 = 1;var num2 = new Number("1");console.log(typeof num1,typeofnum2);//->"number" "object"  

3) in the prototype inheritance of the class, the result of instanceof detection is actually inaccurate.

123 functionFn() {}var f = new Fn;console.log(f instanceofArray);//->false f不是一个数组,它就是一个普通的实例(普通的对象)

Although FN inherits an array, F does not have a length and a numeric index, so f should not be an array, but the result of instanceof detection is true because F is not an array, but an array can be found on the prototype chain of F.

12345 functionFn() {}Fn.prototype = new Array;//->Fn子类继承了Array这个父类中的属性和方法var f = new Fn;console.log(f instanceofArray);//->true

  

3, Object.prototype.toString.call (value), locate the ToString method on the Object prototype, let the method execute, and let the this in the method change to value (value-> Is that we want to detect the value of the data type)

Object.prototype.toString used to determine which built-in property the object value belongs to, and it returns a JSON string-"[Object data Type]".

Because many reference types override the Tostrong method of object inheritance, we usually use call or apply to borrow the Object.prototype.toString function to determine the data type.

Of course, the default premise of this invocation is that Object.prototype.toString is not overridden.

ToString: A method that converts a method to a string data type
Each data type has a ToString method on the prototype of its class, for example: Number.prototype/string.prototype/array.prototype/function.prototype ...
In addition to ToString on object, ToString on other classes of prototypes is the meaning of converting the current data value to a string

Null and undefined comparisons are special: they belong to the class null/undefined the prototype also has ToString, but not let us use it, not only that the prototype of the class is actually shielded

The tostring of an HTML element object: Although its prototype chain is long, there is no ToString on other classes ' prototypes, only at the bottom object.prototype.

, ToString on Object.prototype
1234567 var  < Code class= "JavaScript plain" >odiv = document.getElementById ( Code class= "JavaScript Plain"); odiv.tostring ();   //-> call is actually Object.prototype.toString ...  //alert, document.write these two kinds of output is actually to output the content first converted to a string, and then output the <br> alert ([]);   //-> "" alert ( true ";   //-> "true" alert ({});   //-> This is called "[Object Object]"

 

The tostring variable is defined for ease of writing while reducing the performance loss of the scope chain retrieval var = object.prototype.tostring;console.log (Tostring.call (1));//[ Object Number]console.log (Tostring.call (undefined));//[object Undefined]console.log (Tostring.call (null));//[ Object Null]console.log (Tostring.call (false));//[object Boolean]console.log (Tostring.call ("s"));//[object String] Console.log (Tostring.call ({})),//[object Object]console.log (Tostring.call (/[a]/g));//[object Regexp]console.log ( Tostring.call (function () {}));//[object Function]

Simple implementation of IS series function

After understanding how data types are detected, let's simply implement the IS series detection function.

var dataType = {' [Object Null] ': ' null ', ' [Object Undefined] ': ' Undefiend ', ' [Object Boolean] ': ' Boolean ', ' [object number] ': ' Number ', ' [object string] ': ' String ', ' [Object function] ': ' function ', ' [Object array] ': ' array ', ' [Object Date] ': ' Date ', ' [Object RegExp] ': ' RegExp ', ' [objec T object] ': ' object ', ' [object Error] ': ' Error '}, toString = object.prototype.tostring;function type (obj) {return Datatype[tostring.call (obj)];}        Generate is series functions function Createvalidtype () {for (Var p in DataType) {var objType = P.slice (8,-1); (function (objType) {window[' is ' + objType] = function (obj) {return type (obj) = = = = = = Objtype.tolow            Ercase (); }}) (ObjType)}}createvalidtype (); Console.log (IsObject ({}));//trueconsole.log (IsDate (New Date ()));//trueconsole. Log (Isboolean (false));//trueconsole.log (isstring (1));//falseconsole.log (IsError (1));//falseconSole.log (IsError (New Error ())),//trueconsole.log (IsArray ([]));//trueconsole.log (IsArray (1));//false 

The above code respectively implements IsNull, isundefined, Isboolean, Isnumber, isstring, Isfunction, IsArray, IsDate, Isregexp, IsObject, IsError these 11 detection functions. The type function is also implemented to detect the data type.

Console.log (Type ({})),//"Object" Console.log (Type (new Date ())),//"Date" Console.log (Type (false));/"Boolean" Console.log (Type (1));//"Number" Console.log (type (1));//"Number" Console.log (Type (new error ()));/"Error" Console.log (Type ([]));//"Array" Console.log (type (1));//"Number"

The Createvalidtype function skillfully uses the characteristics of the closed packet to save the data state, and generates the IS series function.

Reprinted from: http://www.cnblogs.com/allenlei/p/6161022.html

Several ways of detecting data types in JS and their advantages and disadvantages "turn"

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.