JavaScript Data type Detection

Source: Internet
Author: User
Tags object object

There are two values for data types in javascript:

A: Basic data type: number, String, Boolean, Undefined, Null;

B: Reference type data: Object, Array, Function, Date, REGEXP;

How do you check which data type the variable belongs to ....

1.typeof method

typeof can only detect basic data types and return "object" to reference type data;

/*-Basic type data-*/var str = "abc",     num = n,     bool = False,    Unde;console.log (typeof str);//=> "string" Console.l OG (typeof num); = "Number" Console.log (typeof bool); = "Boolean" Console.log (typeof Unde); = = "undefined"/*-reference type Data-*/function fu () {};var obj = {};var arr = [];console.log (typeof Fu); = "function" Console.log (typeof obj); = "Object" Console.log (typeof arr); = = "Object" Console.log (typeof null); = "Object" Console.log (typeof new Date ()); = "Object" Console.log (typeof new RegExp ()); = "Object"

  

2.instanceof method; Used to judge a constructor prototype属性是否存在另外一个要检测对象的原型链上 ;

functionA () {};functionB () {};varA =NewA ();varb =NewB (); Console.log (ainstanceofA);//= true;Console.log (binstanceofA);//= false;Console.log (AinstanceofObject);//= true;Console.log (binstanceofObject);//= true;//A A, B is inherited from Object

Attention:

A: If the expression obj instanceof Foo 返回true,则并不意味着该表达式会永远返回ture,因为Foo.prototype属性的值有可能会改变 , the value after the change is most likely not exist in obj the prototype chain, then the value of the original expression will become false . In another case, the value of the original expression will change, that is, changing the obj prototype chain of the object, although in the current ES specification, we can only read the prototype of the object can not change it, but with the help of non-standard __proto__魔法属性 , 是可以实现的 . For example 执行obj.__proto__ = {}之后 ,obj instanceof Foo就会返回false了。

B: instanceof和多全局对象 (interaction between multiple frames or multiple windows); In a browser, our script may need to interact between multiple window. Multiple windows mean multiple global environments, and different global environments have different global objects, with different built-in type constructors. This may cause some problems. For example, the expression is [] instanceof window.frames[0].Array returned false because Array.prototype !== window.frames[0].Array.prototype , therefore, you have to use Array.isArray(myObj) or Object.prototype.toString.call(myObj) === "[object Array]" to determine whether the myobj is an array.

function A () {};var a = new A (); A.prototype = {};console.log (a instanceof a); = = False;var A2 = new A (); Console.log (A2 instanceof a); = true;

3.constructor method; The corresponding constructor of the instance obj is obtained by obj.constructor;

Note: In the case of modifying the prototype chain of constructor A and not showing the modification a.prototype.constructor, the result will not be what we want;

function A () {};var a = new A (); Console.log (A.constructor); = = function A () {};function B () {}; A.prototype = new B (), var a1 = new A (); Console.log (A1.constructor); = = function B () {}; A.prototype.constructor = A;console.log (a1.constructor); = = function A () {};

4.{}.tostring | | Object.prototype.toString (recommended) returns a String representing the object

varots =Object.prototype.toStringots.call (11);//= "[Object number]";Ots.call ("string");//= = "[Object String]";Ots.call (false);//= = "[Object Boolean]";varaaa//declaration not assigned valueOts.call (AAA);//= "[Object Undefined]";Ots.call (NULL);//= = "[Object Null]";Ots.call ({});//= "[Object Object]"Ots.call ([]);//= = "[Object Array]"Ots.call (functionA () {});//= = "[Object Function]"

Fill in the usual data type judgments

/* Data Type Detection */(function (w) {var ots = Object.prototype.tostring,type = {};/* basic data type: number, String, Boolean, Undefined, Null */type.isnumber =  function (o) {return (o = = = 0 | | o) && (o.constructor = = number);}; type.isstring = function (o) {return (o = = = "" | | o) && (o.constructor = = = String); }; Type.isboolean = function (o) {return (o = = = False | | o) && (o.constructor = = = Boolean);}; type.isundefined = function (o) {//Cannot call functions in global Environment return typeof (o) = = = ' undefined ';}; Type.isnull = function (o) {return o = = = = null;};/ * Reference Data type: Object, Array, Function*/type.isobiect = Function (o) {return o && (o.constructor = = = Object | | ots.call (o) = = = "[Object Object]");}; Type.isarray = function (o) {return o && (o.constructor = = = = Array | | ots.call (o) = = = "[Object Array]");}; type.isfunction = function (o) {return o && (o.constructor = = = function);}; W.type = Type;}) (window);

  

JavaScript data type detection

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.