Several methods of detecting data types in JS and their advantages and disadvantages summary _javascript skills

Source: Internet
Author: User
Tags arrays instance method object object

1. typeof operator used to detect data types

typeof value return value is first a string, followed by the corresponding data type, such as: "Number", "string", "Boolean", "Undefined", "object", "function"

Limitations:

1) typeof null-> "Object"

2 detects whether the array or the regular return is "object", so typeof cannot determine if a value is an array

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

2, Instanceof/constructor

Detects whether an instance belongs to a class

Use Instanceof/constructor to detect arrays and regular

Console.log ([] 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, the problem with Object is true
console.log ({}. constructor = = = object);//true<br>console.log ([].constructor = = object);//false

Limitations:

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

var odiv = document.getElementById ("Div1");
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 basic data type cannot be detected with instanceof

Console.log (1 instanceof number);//->false

Array creation in two ways (object, regular, function ...)

For reference data types, we create both of the instances of the owning class, and are all the values of the object data type, without distinction.

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

For basic data types, although either way it is created is an instance of the owning class (a method defined on the prototype of the class can be used), the literal method creates the base data type, and the instance method 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 class, the results of instanceof detection are not accurate

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

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

function Fn () {
}
Fn.prototype = new ARRAY;//->FN subclass inherits the properties and methods in this parent class of Array
var f = new Fn;
Console.log (f instanceof Array);//->true

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

Object.prototype.toString is often 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 inherited by object, we usually use call or apply to borrow the Object.prototype.toString function to determine the data type.

Of course, the default prerequisite for such a call is that Object.prototype.toString is not overridden.

ToString: A method that is converted to a string data type

Each data type belongs to the prototype of the class has the ToString method, for example: Number.prototype/string.prototype/array.prototype/function.prototype ...

In addition to ToString on object, ToString on other class prototypes is the meaning of converting the current data value to a string

The special of NULL and undefined comparison: they belong to the prototype of the class null/undefined also have ToString, but not let us use it, not only that the prototype of the class has been shielded

ToString of an HTML element object: Although its prototype chain is long, there is no ToString on the prototype of the other class, only at the bottom Object.prototype

var odiv = document.getElementById ("Div1");
Odiv.tostring (); -> call is actually Object.prototype.toString
... Alert, document.write These two kinds of output in fact is to output the content first into a string, and then output <br>
alert ([]);//-> "" "
alert (true);//- > "True"
alert ({});//-> this will call the ToString on Object.prototype-> "[Object Object]"
// The toString variable is defined for easy writing, while reducing the performance loss of the search for the scope chain.
var toString = 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 of detection functions.

var dataType = {' [Object Null] ': ' null ', ' [Object Undefined] ': ' Undefiend ', ' [Object Boolean] ': ' Boolean ' , ' [Object number] ': ' Number ', ' [Object String] ': ' String ', ' [Object Function] ': ' function ', ' [Object A Rray] ': ' array ', ' [Object Date] ': ' Date ', ' [Object RegExp] ': ' RegExp ', ' [Object Object] ': ' object ', ' [
Object ERROR] ': ' Error '}, toString = Object.prototype.toString; function type (obj) {return datatype[tostring.call (obj)];}//Generate is series function Createvalidtype () {for (Var p in Datat
    ype) {var objType = P.slice (8,-1);
      (function (objType) {window[' is ' + objType] = function (obj) {return type (obj) = = Objtype.tolowercase ();
}}) (ObjType)} createvalidtype ();
Console.log (IsObject ({}));//true Console.log (IsDate (New Date ());//true Console.log (false); Isboolean
Console.log (isstring (1));//false Console.log (IsError (1));//false Console.log (New Error ()); IsError Console.log (iSarray ([]));//true Console.log (IsArray (1));//false 

The code above 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 ({});//"Object"
Console.log (Type (new Date ());//"Date"
Console.log (FALSE);//" Boolean "
Console.log" (Type (1));//"Number"
Console.log (Type (1));//"Number"
Console.log (Type (new Error ());//"Error"
Console.log ([]);//"Array"
Console.log (Type (1));/"Number"

Createvalidtype function skillfully uses closure to save data state characteristics, batch generation is series function.

The above is a small set of JS to introduce the detection data types of several ways and advantages and disadvantages of a summary, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.