Home  >  Article  >  Web Front-end  >  How to get the type of javascript variable

How to get the type of javascript variable

青灯夜游
青灯夜游Original
2021-10-28 17:47:048362browse

Methods to obtain JavaScript variable types: 1. Use the typeof operator, syntax "typeof variable"; 2. Use jQuery's "$.type()" method; 3. Get the type through the constructor.

How to get the type of javascript variable

The operating environment of this tutorial: windows7 system, javascript1.8.5&&jquery1.10.0 version, Dell G3 computer.

In JavaScript, how to accurately obtain the type name of a variable is a frequently asked question.

But often it is not possible to obtain the precise name of a variable, or the method in jQuery must be used. Here I The three methods of obtaining variable types through typeof, jQuery.type and constructors will be introduced in detail.

I hope it can help you.

At first glance when I saw the question, some Students may think of the typeof operator.


Use typeof to obtain the basic type

In the JavaScript language, it is given to use the typeof operator to obtain the basic type. The type name. (Note that it is not a basic type)

This is all the usage of typeof

01-typeof.htm

console.log('typeof of 10 ~~~~' +typeof 10);
console.log('typeof of "a" ~~~~' +typeof 'a');
console.log('typeof of true ~~~~' +typeof true);
console.log('typeof of {} ~~~~' +typeof {});
console.log('typeof of /123/ ~~~~' +typeof /123/);
console.log('typeof of function(){} ~~~~' +typeof function(){});
console.log('typeof of undefined ~~~~' +typeof undefined);
console.log('typeof of null ~~~~' +typeof null);

This is the result

According to the above printing results, summarize the following points to pay attention to

  • typeof (reference type) Except for functions, they are all 'object', such as typeof /123/

  • typeof null is 'object'

  • typeof undefined is 'undefined', usually, if you use two equal signs, null = = undefined is true.

  • Common usage of converting to numbers is "10"-0. If the conversion is not successful, NaN is returned. Due to a characteristic of NaN: NaN != NaN, so the judgment Common practices for success or failure of conversion: (This is also what I found by looking at the jQuery source code. Reading the jQuery source code 100 times is not enough)
    ("10x" - 0) == ("10x" - 0 ); // The result is false!

Use the method $.type()

## in jQuery #Now look at how jQuery does it

// 先申明一个对象,目的是用来做映射
var class2type = {};
// 申明一个core_toString() 的方法,得到最原始的toString() 方法,因为在很多对象中,toStrintg() 已经被重写 
var core_toString() = class2type.toString;
// 这里为 toStrintg() 后的结果和类型名做一个映射,申明一个core_toString() 后的结果,而值就是类型名
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

Because the Object.prototype.toString() method call result is as follows

var core_toString = {}.toString;
console.log( core_toString.call(1) );
console.log( core_toString.call("11") );
console.log( core_toString.call(/123/) );
console.log( core_toString.call({}) );
console.log( core_toString.call(function(){}) );
console.log( core_toString.call([]) );
console.log( core_toString.call(true) );
console.log( core_toString.call(new Date()) );
console.log( core_toString.call(new Error() ));
console.log( core_toString.call(null) );
console.log( core_toString.call(undefined) );
console.log( String(null) );
console.log( String(undefined) );

The above print result is the same as

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

This is the core method of jQuery.type

type: function( obj ) {
    if ( obj == null ) {
        return String( obj );
    }
    // Support: Safari <= 5.1 (functionish RegExp)
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[ core_toString.call(obj) ] || "object" :
        typeof obj;
},

Note, why null or undefined are discussed separately, because in some versions In the browser


console.log(core_toString.call(null));
console.log(core_toString.call(undefined));

This will report an error!

If it is an object type, another: Because in some lower version browsers ,typeof /123/ will return "function" instead of "object", so you need to determine whether it is a function. You must understand that

typeof obj === function is not discussed for functions, because functions The type itself can be obtained through typeof.

typeof obj === "object" || typeof obj === "function" ?
        class2type[ core_toString.call(obj) ]

It will directly return the result of the key-value pair in class2type. If not, then it must be the basic type, and it can be obtained through typeof.

class2type[ core_toString.call(obj) ] || "object" :
// 这是防止一些未知情况的,如果未取到,就返回object

But

jQuery.type There is a big flaw

This is a custom type

function Person(){
   this.name = &#39;pawn&#39;;
}
var p = Person.toString();

// Note that [object Object] will be printed here, Through the above method, the precise custom type cannot be obtained

This is also a big flaw!

Next, we obtain the precise type through the constructor

Get the type through the constructor

Before understanding this method, you need to understand two points

prorotype prototype attribute

We know that any object or function directly or indirectly inherits from Object or Function (in fact, Function ultimately inherits from Object, which belongs to the knowledge of the prototype chain). Then, any object has a prototype object __proto__ (this object is only exposed in chrome and firefox, but also exists in other browsers). This prototype object is the prototype attribute of the constructor of this object (this may be a bit confusing) .

Since any function has a prototype attribute prototype, and this prototype attribute has a default attribute constructor, which is a reference to this function, see the following code

  function Person(){
      this.name = &#39;pawn&#39;;
  }
  console.log(Person.prototype.constructor === Person);

Found that these two things are actually the same thing

However, in some cases, you need to write like this

  function Person(){
      this.name = &#39;pawn&#39;;
  }
  Person.protype = {
      XX: ... ,
      xx: ... ,
      ...
  }

Doing so will overwrite the original prototype method, then construcor will It no longer exists. This is the object that must be explicitly declared.

  Person.protype = {
      construction: Person,
      XX: ... ,
      xx: ... ,
      ...
  }

In jQuery, this is how it is done.

  jQuery.fn = jQuery.prototype = {
    constructor: jQuery,
    init: function( selector, context, rootjQuery ) {
        var match, elem;

The method of encapsulating jQuery objects is also very worthwhile. Research


    Function.prototype.toString()

Note that this is no longer familiar with [object Object], but It has been rewritten.

也就是,如果调用一个函数的toString() 方法.那么就会打印这个函数的函数体.


好了,经过上面两个步骤,你明白我要做什么了吗?

如何通过构造函数来获得变量的类型?

判断是否是基本类型

   var getType = function(obj){
       if(obj == null){
          return String(obj);
       }
       if(typeof obj === &#39;object&#39; || typeof obj === &#39;fucntion&#39;){
           ...
       }else{
           // 如果不是引用类型,那么就是基本类型
           return typeof obj
       }
   }

如果是对象或者函数类型

   function Person(){
       this.name = &#39;pawn&#39;;
   }
   var p = new Person();
   console.log(p.constructor);

现在要做的事 : 如何将Person 提取出来呢?
毋庸置疑,字符串切割那一套肯定可以办到,但是太 low 啦!
这里,我使用正则将Person提取出来

 var regex = /function\s(.+?)\(/
   function Person(){
    this.name = &#39;pawn&#39;;
   }
   var p = new Person();
   var c = p.constructor
   var regex = /function\s(.+?)\(/;
   console.log(&#39;|&#39; + regex.exec(c)[1] + &#39;|&#39;);

使用name

其实,除了上面的正则,每个函数还有一个name属性,返回函数名,但是ie8 是不支持的.

因此上面的代码可以写为:

var getType = function(obj){
    if(obj == null){
        return String(obj);
    }
    if(typeof obj === &#39;object&#39; || typeof obj === &#39;function&#39;){ 
        var constructor = obj.constructor;
        if(constructor && constructor.name){
            return constructor.name;
        }
        var regex = /function\s(.+?)\(/;
        return regex.exec(c)[1];
    }else{
        // 如果不是引用类型,那么就是基本;类型
        return typeof obj;
    }
};

但是上面的代码太丑啦,将其简化

简化

var getType = function(obj){
    if(obj == null){
        return String(obj);
    }
    if(typeof obj === &#39;object&#39; || typeof obj === &#39;function&#39;){ 
        return obj.constructor && obj.constructor.name.toLowerCase() || 
          /function\s(.+?)\(/.exec(obj.constructor)[1].toLowerCase();
    }else{
        // 如果不是引用类型,那么就是基本类型
        return typeof obj;
    }
};

还是比较麻烦,继续简化

var getType = function(obj){
    if(obj == null){
       return String(obj);
    }
    return typeof obj === &#39;object&#39; || typeof obj === &#39;function&#39; ?
      obj.constructor && obj.constructor.name && obj.constructor.name.toLowerCase() ||
          /function\s(.+?)\(/.exec(obj.constructor)[1].toLowerCase():
      typeof obj;
};

好了,已经全部弄完了,写个代码测试一下:

function Person(){
    this.name = &#39;pawn&#39;;
}
var p = new Person();

console.log(getType(p));
console.log(getType(1));
console.log(getType("a"));
console.log(getType(false));
console.log(getType(/123/));
console.log(getType({}));
console.log(getType(function(){}));
console.log(getType(new Date()));
console.log(getType(new Error()));
console.log(getType( null));
console.log(getType( undefined));

【推荐学习:javascript高级教程

The above is the detailed content of How to get the type of javascript variable. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn