Determination of variable types in javascript

Source: Internet
Author: User

Determination of variable types in javascript

 

In JavaScript, there are 5 basic data types and 1 complex data type. The basic data types include:Undefined,Null,Boolean,NumberAndString; The complex data type isObject,ObjectIt also subdivided into many specific types, such:Array,Function,DateAnd so on. Today we will discuss how to determine the type of a variable.

Before explaining various methods, we first define several test variables to see how the subsequent methods can parse the types of variables, the following variables almost include the types we commonly use in actual encoding.

var num  = 123;var str  = 'abcdef';var bool = true;var arr  = [1, 2, 3, 4];var json = {name:'wenzi', age:25};var func = function(){ console.log('this is function'); }var und  = undefined;var nul  = null;var date = new Date();var reg  = /^[a-zA-Z]{5,20}$/;var error= new Error();
1. Use typeof Detection

We usually use the mosttypeofCheck the variable type. This time, we also usetypeofCheck variable type:

console.log(    typeof num,     typeof str,     typeof bool,     typeof arr,     typeof json,     typeof func,     typeof und,     typeof nul,     typeof date,     typeof reg,     typeof error);// number string boolean object object function undefined object object object object

From the output results, arr, json, nul, date, reg, and error are all detectedobjectType. Other variables can be correctly detected. If the variable is requirednumber,string,boolean,function,undefined, Json type, you can useTypeof. Other variables cannot determine the type, including null.

And,TypeofYes.arrayAndJson type. Because when the typeof variable is used, both the array and json types are output.object.

2. Use instance detection

In JavaScript, the typeof operator is used to judge the type of a variable. When the typeof operator is used, a problem occurs when the reference type storage value is used. No matter what type of object is referenced, it returns "object ". ECMAScript introduces another Java operator instanceof to solve this problem. The instanceof operator is similar to the typeof operator and is used to identify the type of the object being processed. Unlike the typeof method, the instanceof method requires developers to explicitly confirm that the object is of a specific type. For example:

function Person(){}var Tom = new Person();console.log(Tom instanceof Person); // true

Let's take a look at the following example:

function Person(){}function Student(){}Student.prototype = new Person();var John = new Student();console.log(John instanceof Student); // trueconsole.log(John instancdof Person);  // true

instanceofIt can also detect multi-layer inheritance relationships.

Okay, let's use it.instanceofCheck the above variables:

console.log(    num instanceof Number,    str instanceof String,    bool instanceof Boolean,    arr instanceof Array,    json instanceof Object,    func instanceof Function,    und instanceof Object,    nul instanceof Object,    date instanceof Date,    reg instanceof RegExp,    error instanceof Error)// num : false // str : false // bool : false // arr : true // json : true // func : true // und : false // nul : false // date : true // reg : true // error : true

From the preceding running results, we can see that the num, str, and bool types are not detected, but we can use the following method to create num to detect the types:

var num = new Number(123);var str = new String('abcdef');var boolean = new Boolean(true);

At the same time, we also need to see that und and nul are the Object types to be detected, so true is output, because js does not haveUndefinedAndNullBecause both und and nul belong to the Object type, true is output.

3. Use constructor Detection

In useinstanceofWe cannot detect the variable type when detectingnumber, 'String ',bool. Therefore, we need to solve this problem in another way.

Constructor is a property of the prototype object and points to the constructor. However, based on the order of Instance Object Search attributes, if the instance object does not have instance attributes or methods, it will be searched on the prototype chain. Therefore, the instance object can also use the constructor attribute.

Let's output it first.num.constructorContent, that is, what is the constructor of a numeric variable like:

function Number() { [native code] }

We can see that it pointsNumberSo we can usenum.constructor==NumberTo determine whether num is of the Number type, and other variables are similar:

Function Person () {} var Tom = new Person (); // undefined and null do not have the constructor Attribute console. log (Tom. constructor = Person, num. constructor = Number, str. constructor = String, bool. constructor = Boolean, arr. constructor = Array, json. constructor = Object, func. constructor = Function, date. constructor = Date, reg. constructor = RegExp, error. constructor = Error); // All results are true

From the output results, we can see that except for undefined and null, other types of variables can be used.constructorDetermine the type.

However, using a constructor is not safe, because the constructor attribute can be modified, which may result in incorrect results. For example:

function Person(){}function Student(){}Student.prototype = new Person();var John = new Student();console.log(John.constructor==Student); // falseconsole.log(John.constructor==Person);  // true

In the preceding example, the constructor in the Student prototype is changedPersonAs a result, the real constructor of the Instance Object John cannot be detected.

At the same time, with instaceof and construcor, the identified array must be declared on the current page! For example, a page (parent page) has a framework that references a page (Child page) and declares an array in the Child page, assign the value to a variable on the parent page. Then, the variable is determined. Array = object. constructor; returns false;
Cause:
1. array is a type of referenced data. In the transfer process, only the reference address is transmitted.
2. The address referenced by the Array native object on each page is different. The constructor corresponding to the array declared on the subpage is the Array object of the subpage; the parent page is used for judgment. The Array used is not equal to the Array of the Child page. Remember, otherwise it is difficult to track the problem!

4. Use Object. prototype. toString. call

No matter what this is, let's see how it detects the variable type:

console.log(    Object.prototype.toString.call(num),    Object.prototype.toString.call(str),    Object.prototype.toString.call(bool),    Object.prototype.toString.call(arr),    Object.prototype.toString.call(json),    Object.prototype.toString.call(func),    Object.prototype.toString.call(und),    Object.prototype.toString.call(nul),    Object.prototype.toString.call(date),    Object.prototype.toString.call(reg),    Object.prototype.toString.call(error));// '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]'// '[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'

From the output results,Object. prototype. toString. call (variable)The output is a string with an array in it. The first parameter is the Object, and the second parameter is the type of the variable. In addition, all types of variables are detected, we only need to retrieve the second parameter. Or you can useObject.prototype.toString.call(arr)==object ArrayTo check whether the arr variable is an array.

Now let's take a look at how ECMA defines it.Object.prototype.toString.callOf:

Object. prototype. toString () When the toString method 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)

The above Specification defines Object. prototype. toString behavior: first, obtain an internal attribute of the object [[Class], and then, based on this attribute, returns a string similar to "[object Array]" as the result (we should all know after reading the ECMA standard, [[] is used to indicate the attributes used inside the language and which cannot be accessed externally, is called "Internal attribute "). With this method, combined with call, we can obtain the internal attribute [[Class] of any object, and then convert the type detection to string comparison to achieve our goal.

5. Implementation of $. type in jquery

In jquery,$.typeTo let us detect the type of the variable:

console.log(    $.type(num),    $.type(str),    $.type(bool),    $.type(arr),    $.type(json),    $.type(func),    $.type(und),    $.type(nul),    $.type(date),    $.type(reg),    $.type(error));// number string boolean array object function undefined null date regexp error

Are you familiar with the output results? Yes, it is used aboveObject. prototype. toString. call (variable)The second parameter of the output result.

Here we will first compare the Results Detected by all the above methods. The horizontal layout is the detection method used, and the vertical bars are various variables:

Type Determination Typeof Instanceof Constructor ToString. call $. Type
Num Number False True [Object Number] Number
Str String False True [Object String] String
Bool Boolean False True [Object Boolean] Boolean
Arr Object True True [Object Array] Array
Json Object True True [Object Object] Object
Func Function True True [Object Function] Function
Und Undefined False - [Object Undefined] Undefined
Nul Object False - [Object Null] Null
Date Object True True [Object Date] Date
Reg Object True True [Object RegExp] Regexp
Error Object True True [Object Error] Error
Advantages Easy to use and direct output of results Can detect complex types All types can be detected. All types detected -
Disadvantages Too few detected types Basic Types cannot be detected and cannot be cross-iframe Cannot span iframe, and constructor is easy to modify In IE6, undefined and null are all objects. -

In this way, we can see the differences between different methods, andObject.prototype.toString.callAnd$typeThe output result is very similar. Let's take a look at how the $. type method is implemented in jquery (version 2.1.2:

// The instance object is the var class2type ={}; var toString = class2type that can directly use the method on the prototype chain. toString; // some code is omitted... type: function (obj) {if (obj = null) {return obj +;} // Support: Android <4.0, iOS <6 (funish ish RegExp) return (typeof obj = object | typeof obj = function )? (Class2type [toString. call (obj)] | object): typeof obj;}, // omitting some code... // Populate the class2type mapjQuery. each (Boolean Number String Function Array Date RegExp Object Error. split (), function (I, name) {class2type [[object + name +] = name. toLowerCase ();});

Let's take a look.JQuery. eachThis part:

// Populate the class2type mapjQuery. each (Boolean Number String Function Array Date RegExp Object Error. split (), function (I, name) {class2type [[object + name +] = name. toLowerCase () ;}); // After the loop, the value of 'class2type' is: class2type = {'[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Function]': 'function', '[object Array]': 'array ', '[object Date]': 'date', '[object RegExp]': 'regexp', '[object Object]': 'object', '[object Error]': 'error '}

Let's take a look.typeMethod:

// Type Implementation type: function (obj) {// If the input is null or undefined, the string of this object is directly returned // that is, if the input object obj is undefined, returns undefined if (obj = null) {return obj +;} // Support: Android <4.0, iOS <6 (funish ish RegExp) // regExp of earlier versions returns the function type; the previous version has been corrected. The object type is returned. // if the object type detected by typeof is object or function, the value of class2type is returned, otherwise, return the type of typeof detection. return (typeof obj = object | typeof obj = function )? (Class2type [toString. call (obj)] | object): typeof obj ;}

Whentypeof obj === object || typeof obj === functionAnd returnsclass2type[ toString.call(obj). At this point, we should understand why Object. prototype. toString. call and $. type are so similar. In fact, jquery usesObject.prototype.toString.callTo convert the '[ object Boolean] 'type to 'boolean' type and return the result. If class2type does not store the type of this variable, "object" is returned ".
Except for the "object" and "function" types, typeof is used for detection. That isnumber,string,booleanType Variable. Use typeof.

 

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.