How to judge the type of JS object

Source: Internet
Author: User

In the process of writing a JS program, you may often need to determine the type of an object, for example, you write a function, you need to determine the different types of parameters to write different code.

The first thing you might think of is the typeof operator, which looks at the following example:

  <script type= "Text/javascript" >var object = {};var b = True;alert (typeof object + "" + typeof B);  </script>
The results are as follows:

As you can see from the above results, the type of the object can be displayed with the typeof operator, so what is the result of the typeof operator scope null and undefined?

/*var object = {};var b = True;alert (typeof object + "" + typeof B); */alert (typeof null + "" + typeof undefined)

The typeof operator acts on NULL to actually display "object" (this seems unscientific, I thought it would show "null"), which is used for undefined to display "undefined" (this fits our desired result), So when you use the TypeOf operator to determine the type of an object, be especially careful, because this object might be null. The above gives only a subset of the results of TypeOf acting on these objects, the table below lists the TypeOf operators acting on Boolean, number, String, Array, Date, REGEXP, Object, function, NULL, Results of undefined (interested readers can test themselves):


From the results of the above table, we can see that array, Date, and regexp are all objects, why not the type of the direct display object? This leads to another JS operator: theinstanceof operator, which is used to determine whether an object is a certain type of object, evaluates to TRUE or FALSE. First look at the following:

var now = new Date (), var pattern =/^[\s\s]*$/;var names = [' Zq ', ' John '];alert (now instanceof date) + "" + (Pattern INS tanceof RegExp) + "" + (names instanceof Array));

Obviously through this instanceof is able to judge the type of object, but this can only be judged in addition to the basic type (including the string type) of other types, he can not judge the basic type. But instanceof is not always able to judge, consider a framework of the case, to determine its type of object is another frame passed over the object, first look at the following example.

Main.html

<!doctype html>
Frame1.html

<!doctype html>

Frame2.html

<!doctype html>


The names object is in the FRAME1 framework, which is created by the array of the FRAME1 framework, and if the names object is taken to the array in frame2, it is obvious that names is not an instance of the array in Frame2, Think Frame1 and frame2 is not the same and array, from the 2nd realistic result can be clearly seen names is his own frame instance, from the 3rd output can be seen frame1 array and frame2 array is different. What do you do when you encounter the above-mentioned cross-frame comparison? We can not always take the frame corresponding to the array to do the comparison, there is a necessary way to solve the above problem, see the following code:

   var toString = {}.tostring;   var now = new Date ();   Alert (Tostring.call (now))

{}.tostring represents one of the basic methods for getting the ToString method on object objects when this method is used, Tostring.call (now) means calling the ToString method. Calling the most native ToString () of the Date object (this method is the method above the object) method can display a string of type [object Date], and if it is an array, it will produce the word "Object Array". This means that the above operation will show something like [object Class], so we just have to judge the string to know its type? This allows you to write the following tool classes:

Tools.js

var tools = (function (undefined) {    var class2type = {},        tostring = {}.tostring;        var fun = {        type:function (obj) {            return obj = = NULL | | obj = = = Undefined     &n bsp;                   string (obj): class2type [Tostring.call (obj)]        },        isarray:function (obj) {            return fun.type (obj) = = = = "Array";     & nbsp  },        isfunction:function (obj) {             return fun.type (obj) = = = "function";        },         each:function (arr, callback) {&Nbsp;           var i = 0,            & nbsp;    haslength = arr.length? true:false;            if (!callback | | (typeof callback!== ' function ') | | !haslength) {                return;             }            for (i = 0; i< Arr.length; i++) {                if (Callback.call (Arr[i], I, arr[i]) = = = False) {                         break;                }             }        }    };    fun.each ("Boolean number String Array Date RegExp Object Function ". Split ("), Function (i, name) {       &NB Sp;class2type["[Object] + name +"] "= Name.tolowercase ();    });    return fun;}) ();
Tools provide methods such as type,isarray,isfunction to determine the type of object and, depending on the actual needs, can add methods that need to determine the type. The type accepts an obj parameter, which returns the actual type of the object in lowercase, such as if you need to determine the type of the object is an array, then this method returns an array.

Based on the tool class provided above, rewrite the above example again:

Fram2.html

<!doctype html>

The type of the object can be easily judged by the above based on the class.

Note: Elements such as alert are not judged in IE.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How to judge the type of JS object

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.