search
HomeWeb Front-endJS TutorialHow to get the type of javascript variable

How to get the type of javascript variable

Oct 28, 2021 pm 05:47 PM
javascriptVariable type

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use