Table of Contents
Use typeof to obtain the basic type
Use the method $.type()
Get the type through the constructor
prorotype prototype attribute
判断是否是基本类型
如果是对象或者函数类型
使用name
简化
Home Web Front-end JS Tutorial How to get the type of javascript variable

How to get the type of javascript variable

Oct 28, 2021 pm 05:47 PM
javascript Variable 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);
Copy after login

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;
Copy after login
// 这里为 toStrintg() 后的结果和类型名做一个映射,申明一个core_toString() 后的结果,而值就是类型名
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
Copy after login

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) );
Copy after login

The above print result is the same as

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

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;
},
Copy after login

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));
Copy after login

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) ]
Copy after login

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
Copy after login

But

jQuery.type There is a big flaw

This is a custom type

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

// 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);
Copy after login

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: ... ,
      ...
  }
Copy after login

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: ... ,
      ...
  }
Copy after login

In jQuery, this is how it is done.

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

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
       }
   }
Copy after login

如果是对象或者函数类型

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

现在要做的事 : 如何将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;);
Copy after login

使用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;
    }
};
Copy after login

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

简化

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;
    }
};
Copy after login

还是比较麻烦,继续简化

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;
};
Copy after login

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

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));
Copy after login

【推荐学习: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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles