Several ways and advantages and disadvantages of detecting data types in JS

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

Console.log (typeof [+]);//-> "Object"

2, Instanceof/constructor

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

Console.log ([] instanceof Array);//->trueconsole.log (/^$/instanceof RegExp);//->trueconsole.log ([] instanceof Object);//->trueconsole.log ([].constructor = = = = Array);//->trueconsole.log ([].constructor = = = Object);//->false

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

Console.log ({}.constructor = = = Object);//true
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

var odiv = document.getElementById ("Div1");//htmldivelement->htmlelement->element->node->eventtarget- >objectconsole.log (Odiv instanceof htmldivelement);//->trueconsole.log (Odiv instanceof Node);//-> Trueconsole.log (Odiv instanceof Object);//->true

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

Console.log (1 instanceof number);//->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.

var ary = [];var ary = new Array;

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.

var num1 = 1;var num2 = new Number ("1"), Console.log (typeof num1,typeof num2);//-> "number" "Object"

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

function Fn () {}var f = new Fn;console.log (f instanceof Array);//->false f is not an array, it is a normal instance (normal object)

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.

The function Fn () {}fn.prototype = new Array;//->fn subclass inherits the properties and methods in the parent class of the Array var f = new Fn;console.log (f instanceof Array);//- >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.

var odiv = document.getElementById ("Div1"); odiv.tostring (); The call is actually Object.prototype.tostring...//alert, document.write these two kinds of output of the way is actually to output the content first converted to a string, and then output the
alert ([]); , "" alert (true); "True" alert ({}); This is called "[Object Object]" on Object.prototype.

 

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.

Several ways and advantages and disadvantages of detecting data types in JS

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.