JS variable type is judged

Original link: https://www.cnblogs.com/zhangruiqi/p/8027338.html

JS variable type is judged

Summary: 1. General simple to use instanceof or typeof detection (not entirely accurate detection of the two)

2. Use $ .Type completely accurate detection of native js Object.prototype.toString.call or in jquery

In JS, there are five basic types of data, and one kind of complex data types, the basic data types: Undefined, Null, Boolean, Number String, and; complex data type Object, Object further subdivided numerous specific type, such as : Array, Function, Date, and so on. Today we're going to explore, what a way to determine a variable's type.

Before explaining the various methods, we first define a few variables to test to see what type of latter method can resolve into what looks like a variable, the following variables contain almost we used in the actual coding type.

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. Detection typeof

We usually use the most is the use typeof to detect the type of the variable. This time, we also use typeof to detect the type of a 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 point of view of the result output, arr, json, nul, date, reg, error type object is detected as all other variables can be correctly detected. When the need for a variable number, string, boolean, function, undefined, when json type, can be determined using typeof. Other variables are determined not type including null.

There, typeof is not distinguish between the type of array and json. Because this variable using typeof, array, and the type of output is json object.

2. Use instanceof detection

In JavaScript, a variable is determined by the type of try typeof operator will, in use typeof operator using reference type stored value will be a problem, no matter what type of object referenced, which returns "object". ECMAScript introduces another Java instanceof operator to solve this problem. instanceof operator typeof operator with similar type of object being processed for recognition. And typeof method is different, instanceof method requires developers to explicitly confirm the object for a particular type. E.g:

function Person(){

}

var Tom = new Person();

console.log(Tom instanceof Person); // true

Let us look at the following example:

function Person(){
 
}

function Student(){

}

Student.prototype = new Person();

var John = new Student();

console.log(John instanceof Student); // true

console.log(John instancdof Person);  // true

instanceof can also detect multiple layers inheritance relationship.

Well, let's use those variables instanceof detection 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

We can see from the above operating results, num, str bool and did not detect his type, but we use the following way to create num, can detect the type of:

var num = new Number(123);

var str = new String('abcdef');

var boolean = new Boolean(true);

At the same time, we also see that, and nul und type Object detection, true output only because js no such global type Undefined and Null, who belong und nul and Object types, output true.

3. Use the constructor detection

When using instanceof detection variable type, we undetectable number, 'string', bool type. Therefore, we need a different way to solve this problem.

constructor originally property on the prototype object, point constructor. However, according to an example of order attribute to find the object, if there is no instance of an object instance of the property or method, go to find the prototype chain, therefore, an object instance constructor property can be used also.

Let's take a look at the contents of num.constructor output, that is the constructor of the variable type of numbers look like:

function Number() { [native code] }

We can see that it points to the Number constructor, so we can use num.constructorNumber judge num is not a Number type, other variables also similar:
we can see that it points to the Number constructor, so we can use num.constructor
Number Number to determine num is not the type of other variables like this:

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

We can see from the result output, in addition to undefined and null, can use other types of variable type is judged constructor.

But using constructor is not insurance, because the constructor property can be modified, can lead to incorrect results detected, for example:

function Person(){

 
}

function Student(){


}

Student.prototype = new Person();

var John = new Student();

console.log(John.constructor==Student); // false

console.log(John.constructor==Person);  // true

In the above example, Student prototype constructor is modified to point to Person, John instance object can not be detected resulting in true constructor.

At the same time, the use of instaceof and construcor, the array must be judged on the current page statement! For example, a page (parent page) has a frame, which is referenced in a page (subpages), declares an array in the sub-page, and assign it to a variable parent page, then the variable is determined, Array == object.constructor; return false;

the reason:

1, array data belonging to a reference type, in the transfer process, just pass a reference address.

2, the address of each page Array native objects referenced are not the same, the sub-page array declaration, the corresponding constructor, Array object is a sub-page; parent page to be judged, the use does not mean Array Array subpages; remember, otherwise difficult to track the problem!

4. Use Object.prototype.toString.call

Let Whatever this is, let's see how he detected variable types:

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 point of view of the result output, Object.prototype.toString.call (variable) output is a string, there is a string array, the first parameter is Object, the second parameter is the variable type, and, All variables are detected, we only need to remove the second parameter. Or you may use Object.prototype.toString.call (arr) == "object Array" arr detected variable is not an array.

We now look at how the definition of ECMA in Yes Yes Object.prototype.toString.call of:

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, get the object of an internal property [[Class]], and then based on this property, a return similar to "[object Array]" string as the result (read ECMA standard should know, [[]] to indicate the language used in internal, external attributes not directly accessible, known as the "internal property"). Using this method, together with Call, we can achieve any internal attributes of an object [[Class]], and then put into a string comparison type detector in order to achieve our purpose.

5. jquery implemented in the $ .Type

Offers a $ .type in jquery interface, the type to let us detect variables:

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, there is not a familiar feeling? Yes, he is using the results of the above Object.prototype.toString.call (variable) output of the second parameter Yeah.

We come here to compare the results of all of the above method detected, horizontal detection method is used, the variables are vertical:
Here Insert Picture Description
this compare, you better see the difference between the various methods, and it Object.prototype. toString.call and t Y p e lose Out of Knot fruit true of very image I They Come Look Look j q in e r Y 2.1.2 Version this Inside unit Yes How What real Present Result type output really like. Let's look at jquery (2.1.2 version) is how to achieve internal .type method:

// 实例对象是能直接使用原型链上的方法的

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 map

jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {

    class2type[ "[object " + name + "]" ] = name.toLowerCase();

});

 

我们先来看看jQuery.each的这部分:

 

// Populate the class2type map

jQuery.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'

}

 

再来看看type方法:

// 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", returns class2type [toString.call (obj). Here, we should understand why Object.prototype.toString.call and $ .type so much like it, in fact, is to use jquery Object.prototype.toString.call implemented, the '[object Boolean]' type turn into ' boolean 'type and return. Without this type of variable class2type stored, then return to "object".

In addition to "object" and "function" type, other types of use typeof detected. That number, string, boolean type variable, you can use typeof.

Guess you like

Origin blog.csdn.net/weixin_45734493/article/details/102494341