A summary of several methods for judging object types in JavaScript _ basics

Source: Internet
Author: User
Tags arrays

We know that the operators that detect object types in JavaScript are: typeof, Instanceof, and the constructor properties of objects:

1) The typeof operator TypeOf is a unary operator, and the return result is a string indicating the type of the operand. such as: "Number", "string", "Boolean", "Object", "function", "undefined" (can be used to determine whether a variable exists). But TypeOf is limited in its ability to return "object" for the date and regexp types. Such as:

typeof {}; "Object" 
typeof [];//"Object" 

So it works only when you're distinguishing objects from the original type. To area an object type and another object type, you must use a different method. such as: instanceof operator or object of the constructor genus.

2) instanceof operator. The instanceof operator requires that the operand on the left is an object, and that the right-hand operand is the name or constructor of the object class. If object is an instance of class or constructor, the instanceof operator returns TRUE. Returns False if object is not an instance of the specified class or function, or if object is null. Such as:

[] instanceof Array; True 
[] instanceof Object;//True 
[] instanceof RegExp;//False 

Therefore, you can use the instanceof operator to determine whether an object is an array type:

function IsArray (arr) {return 
  arr instanceof Array; 

3) Constructor property. in JavaScript, each object has a constructor property that references the constructor that initializes the object, often used to determine the type of an unknown object. If a given value of knowledge is judged by the typeof operator, it is the original value or object. If it is an object, you can use the constructor property to determine its type. So the function of judging an array can also be written like this:

function IsArray (arr) {return 
  typeof arr = = "Object" && arr.constructor = = Array; 

In many cases, we can use the instanceof operator or the object's constructor property to detect whether an object is an array. For example, many JavaScript frameworks use these two methods to determine whether an object is an array type. However, when an array is detected on a cross frame (cross-frame) page, it fails. The reason is that arrays created in different frames (IFRAME) do not share their prototype properties with each other. For example:

<script>
window.onload=function () {
var iframe_arr=new window.frames[0]. Array;
Alert (Iframe_arr instanceof Array); False
alert (iframe_arr.constructor = = Array);//False
}
</script>


A precise detection method is seen on the Ajaxian, and the ToString () method is invoked across the prototype chain: Object.prototype.toString (). Can solve the cross frame problem above. When Object.prototype.toString (O) executes, the following steps are performed: 1 Gets the class attribute of the object o. 2 connection string: "[object" + result (1) + "]" 3) return result (2) For example:

Object.prototype.toString.call ([]); Return "[Object Array]"
Object.prototype.toString.call (/reg/ig); Return "[Object RegExp]"

In this way, we can write a robust function that determines whether an object is an array:

function IsArray (arr) {return
  Object.prototype.toString.call (arr) = = "[Object Array]";
}


This approach is recognized by a number of JavaScript masters abroad and will be used to detect arrays in the upcoming jquery 1.3. A maintainer of Prototype.js wrote the following function to get the type name of the object

/**
 * Returns internal [[Class]] property of an object
 *
 * Ecma-262, 15.2.4.2
 * Object.prototype.toString ()
 * When
 the "toString" is called, the following steps are taken: 
 * 1. Get the [[Class]] property of this object. 
 * 2. Compute a string value by concatenating the three Strings "[object", result (1), and "]". 
 * 3. return result (2).
 *
 * __getclass (5);//=> "number"
 * __getclass ({});//=> "Object"
 * __getclass (/foo/);//=> "Reg  Exp "
 * __getclass (");//=> "String"
 * __getclass (TRUE);//=> "Boolean"
 * __getclass ([]);//=> "Array"
 * __getclass (undefined);//=> "window"
 * __getclass (Element);//=> "constructor"
 *
 */
function __getclass (object) {return
  Object.prototype.toString.call (object). Match (/^\[object\s (. *) \]$/) [1];
};


Expand to detect various object types:

var is ={
  types: ["Array", "Boolean", "Date", "number", "Object", "RegExp", "String", "Window", "HTMLDocument"]
} ;
for (var i = 0, c; c = is.types[i + +];) {
  Is[c] = (function (type) {return
    function (obj) {return
      Object.prototype.toString.call (obj) = "[Object" + Type + "]";
    }
  ) (c);
}
Alert (IS. Array ([])); True
alert (is. Date (new date)); True
alert (is. REGEXP (/reg/ig)); True


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.