The judgment of variable types in JavaScript

Source: Internet
Author: User

This article official address: Http://www.xiabingbao.com/javascript/2015/07/04/javascript-type

In JavaScript, there are 5 basic data types and 1 complex data types, with basic data types:Undefined, Null, Boolean, number, and The complex data type is Object, which Object also breaks down a number of specific types, such as: Array, Function, Date , and so on. Today we will discuss what method to use to determine the type of a variable.

Before explaining the various methods, we first define a few test variables to see what the latter method can do to resolve the type of the variable, and the following variables almost contain the types we commonly use in actual coding.

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. Using typeof detection

The most common thing we use is the typeof type of detection variable. This time, we also use typeof the type of the detection variable:

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, error are all detected as object types, and other variables can be detected correctly. When a variable is required,,,, or number string JSON type, it can be boolean function undefined judged using typeof . Other variables are not judged by type, including null.

Also,typeof is not distinguishable array json类型 . Because the array and JSON types are output when you use the typeof variable object .

2. Using instance Detection

In JavaScript, judging the type of a variable with the typeof operator, a problem occurs when you store a value with a reference type using the TypeOf operator, which returns "object" regardless of what type of object is referenced. ECMAScript introduced another Java operator, instanceof, to solve this problem. The instanceof operator is similar to the typeof operator to identify the type of object being processed. Unlike the TypeOf method, the Instanceof method requires the developer to explicitly confirm that the object is of a particular type. For example:

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

Let's 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 the relationship between multiple layers of inheritance.

OK, let's use instanceof these variables to detect the above:

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 running results above we can see that num, str and bool do not detect his type, but we use the following method to create NUM, which can be detected by type:

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

At the same time, we also want to see that und and Nul is the object type detected, only output true, because JS does not have Undefined Null such a global type, they und and nul belong to the object type, so output true.

3. Using constructor detection

When using the instanceof detection variable type, we are not detected number , ' string ', bool of type. Therefore, we need a different way to solve this problem.

constructor is originally a property on a prototype object, pointing to the constructor. However, depending on the order of the instance objects, if there is no instance property or method on the instance object, it is searched on the prototype chain, so the instance object can also use the constructor property.

Let num.constructor 's start with the output, that is, what the constructor of a variable of number type looks like:

function Number() { [native code] }

We can see that it points to Number the constructor, so we can use it num.constructor==Number to determine if NUM is the number type, and the other variables are similar:

function Person(){}var Tom = new Person();// undefined和null没有constructor属性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);// 所有结果均为true

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

However, using constructor is not an insurance policy, because the constructor attribute can be modified, resulting in incorrect results detected, such as:

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 example above, the constructor in the student prototype was modified to point to the person, causing the instance object John Real constructor to be detected.

At the same time, using instaceof and Construcor, the determined array must be declared on the current page! For example, a page (parent page) has a frame, the frame refers to a page (sub-page), in the Sub-page declaration of an Array, and assign it to the parent page of a variable, then determine the variable, Array = = Object.constructor; returns false;
Reason:
1, array belongs to the reference data, in the process of delivery, is simply the delivery of the reference address.
2, each page of the array native object refers to the address is not the same, in the sub-page declaration of the array, the corresponding constructor is a sub-page array object, the parent page to judge, the use of the array is not equal to the sub-page array; Remember, it's hard to track the problem!

4. Using Object.prototype.toString.call

Let's start by looking at how he 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 of the results, the Object.prototype.toString.call(变量) output is a string, the string has an array, the first parameter is an object, the second parameter is the type of the variable, and all the variable types are detected, we just need to take out the second parameter. Or you can use Object.prototype.toString.call(arr)=="object Array" to detect whether the variable arr is an array.

Now let's look at how the ECMA is defined Object.prototype.toString.call :

Object.prototype.toString () When the ToString method was called, the following steps is 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 the behavior of Object.prototype.toString: First, get an internal property of the object [[Class]], and then, based on this property, return a similar "[Object Array]" string as a result (it should be known from the ECMA standard that [[]] is used to denote an externally accessible property that is used internally by the language, called an "internal property"). Using this method, and with call, we can obtain the internal properties of any object [[Class]] and then convert the type detection to a string comparison to achieve our goal.

5. Implementation of $.type in jquery

An interface is provided in jquery $.type to 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

See the output, is there a familiar feeling? Yes, he is the Object.prototype.toString.call(变量) second parameter of the result of using the output above.

Let's compare the results of all the above methods, the horizontal is the detection method used, and the vertical row is the individual variables:

Type judgment 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 Simple to use, direct output results Capable of detecting complex types The basic ability to detect all types All types are detected -
Disadvantages Too few types detected The base type is not detected and cannot span the IFRAME Cannot span IFrame, and constructor is easily modified IE6 under Undefined,null are object -

In this comparison, you can see the difference between the different methods, and the Object.prototype.toString.call $type output is really similar to the results. Let's look at how the $.type method is implemented inside jquery (2.1.2 Version):

// 实例对象是能直接使用原型链上的方法的var class2type = {};var toString = class2type.toString;// 省略部分代码...type: function( obj ) {    if ( obj == null ) {        return obj + "";    }    // Support: Android<4.0, iOS<6 (functionish RegExp)    return (typeof obj === "object" || typeof obj === "function") ?        (class2type[ toString.call(obj) ] || "object") :        typeof obj;},// 省略部分代码... // 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 look at this part of Jquery.each First:

// Populate the class2type mapjQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {    class2type[ "[object " + name + "]" ] = name.toLowerCase();});//循环之后,`class2type`的值是: 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‘}

Look again at the type method:

// type的实现type: function( obj ) {    // 若传入的是null或undefined,则直接返回这个对象的字符串    // 即若传入的对象obj是undefined,则返回"undefined"    if ( obj == null ) {        return obj + "";    }    // Support: Android<4.0, iOS<6 (functionish RegExp)    // 低版本regExp返回function类型;高版本已修正,返回object类型    // 若使用typeof检测出的obj类型是object或function,则返回class2type的值,否则返回typeof检测的类型    return (typeof obj === "object" || typeof obj === "function") ?        (class2type[ toString.call(obj) ] || "object") :        typeof obj;}

When typeof obj === "object" || typeof obj === "function" , it returns class2type[ toString.call(obj) . Here, we should understand why Object.prototype.toString.call and $.type so like, in fact, jquery is Object.prototype.toString.call implemented, the ' [Object Boolean] ' type to ' Boolean ' Type and returns. If the Class2type store does not have the type of this variable, it returns "Object".
In addition to the "Object" and "function" types, other types are detected using TypeOf. That is, a number string boolean variable of type, using TypeOf.

This article official address: Http://www.xiabingbao.com/javascript/2015/07/04/javascript-type

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

The judgment of variable types in JavaScript

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.