Table of Contents
Boxing
Unboxing
Type conversion
Logical operators
Arithmetic operator
一些题目
Home Web Front-end JS Tutorial JavaScript skills: unboxing and type conversion

JavaScript skills: unboxing and type conversion

Mar 02, 2022 pm 06:18 PM
javascript

This article brings you relevant knowledge about javascript, which mainly introduces issues related to unboxing and type conversion. Boxing refers to converting basic data types into corresponding Let’s take a look at the operations of reference types. I hope it will be helpful to everyone.

JavaScript skills: unboxing and type conversion

Related recommendations: javascript tutorial

Basic data types: string, number, boolean

Reference type: object, function

Non-existing type: undefined

String, Number, Boolean belong to string, number respectively , boolean are three primitive types of packaging types, and their objects are reference types.

Boxing

Boxing refers to the operation of converting basic data types into corresponding reference types. This process mainly refers to string, The process of packaging number, boolean type data into reference type data through String, Number, Boolean.

// 隐式装箱var s1 = 'Hello World'; 
var s2 = s1.substring(2);
Copy after login

The execution steps of the second line above are actually as follows:

  1. Use new String('Hello World') Create a temporary instance object;
  2. Use the temporary object to call the substring method;
  3. Assign the execution result to s2; Destroy the temporary instance object .

The above steps are converted into code, as follows:

// 显式装箱var s1 = 'Hello World'; 
var tempObj = new String('Hello World');
var s2 = tempObj.substring(2);
Copy after login

Unboxing

Unboxing is to convert the reference type into a basic data type.

About ToPrimitive during the unboxing process

Type conversion

The operator has an expected type for the variables at both ends. In javascript, Any variable that does not meet the type expected by the operator will be implicitly converted.

Logical operators

When performing logical operations, there is only one standard for implicit conversion: Only null, undefined, '', NaN, 0 and false represent false, and other cases are true,for example{} , [].

Arithmetic operator

  1. If both ends of the arithmetic operator are data of type number, the calculation is performed directly;

  2. If there are non-number basic data types at both ends of the arithmetic operator, use Number()# for the non-number operands. ##Carry out boxing, and then unbox the return value into the number type to participate in the calculation;

  3. If there are reference data types at both ends of the arithmetic operator, then the Perform an unboxing operation on the reference type. If the result is a non-

    number type, it will be executed according to Condition 2, otherwise Condition 1 will be executed.

  4. 1 - true 
    // 0, 首先 Number(true) 转换为数字 1, 然后执行 1 - 11 - null 
    // 1,  首先把 Number(null) 转换为数字 0, 然后执行 1 - 01 * undefined 
    //  NaN, Number(undefined) 转换为数字是 NaN , 然后执行 1 * NaN2 * ['5'] 
    //  10, ['5'] 依照ToPrimitive规则进行拆箱会变成 '5', 然后通过 Number('5') 进行拆装箱再变成数字 5123 + {valueOf:()=>{return 10}}   
    // 133  {valueOf:()=>{return 10}} 依照ToPrimitive规则会先调用valueOf,获得结果为10
    Copy after login
When

appears in front of a variable as a unary operator, it means converting the variable to Numbertype

+"10" 	
// 10  同 Number("10")+['5']  
// 5   ['5']依照ToPrimitive规则会变成 '5', 然后通过`Number`的拆箱操作再变成数字 5
Copy after login
String connector

The symbol of the string connector is the same as the

of the arithmetic operator.

    If both ends of the arithmetic operator are data of type
  1. string, connect directly
  2. If there are non-
  3. string# at both ends of the operator ## basic type, use String() to box non-string basic type data, and then unbox the return value into a basic type to participate in string splicing. When
  4. there are reference data types at both ends, the reference type will be unboxed first. If the result is not a string type, then the reference type will be unboxed according to Condition 2 is executed, otherwise condition 1 is executed.
  5. Relational operator

  • #NaN

    and any other type, any relational operation will always return false ( including himself). If you want to determine whether a variable is NaN, you can use Number.isNaN() to determine.

  • null == undefined

    The comparison result is true, in addition, null, undefined The comparison value between and any other result (excluding themselves) is false.

    This is defined by the rules,
    null

    is the type of object, but there will be syntax errors when calling valueOf or toString, here Just remember the result.

  • generally:
    1. 如果算术运算符两端均为number类型的数据,直接进行计算;
    2. 如果算术运算符两端存在非number的基本数据类型,则对非number的运算数使用Number()进行装箱,然后对返回值进行拆箱为number类型,参与计算;
    3. 算术运算符两端存在引用数据类型,则先对引用类型进行拆箱操作,如果结果为非number类型,则根据条件2执行,否则执行条件1
{} == !{}  
// false   Number({}.valueOf().toString())==> NaN , 所以题目等同于 NaN == false , NaN 和 任何类型比较都是 false[] == []  
// false  内存地址不同![] == 0  
// true   ![]==>false , 所以题目等同于 false==0 , Number(false)==>0 ,  所以结果为 true
Copy after login

一些题目

  1. [] == ![]

        - 第一步,![] 会变成 false
        - 第二步,[]的valueOf是[],[]是引用类型,继续调用toString,题目变成: "" == false
        - 第三步,符号两端转换为Number, 得到 0==0
        - 所以, 答案是 true
    Copy after login
  2. [undefined] == false

        - 第一步,[undefined]的valueOf结果为 [undefined],然后[undefined]通过toString变成 '' ,所以题目变成  '' == false
        - 第二步,符号两端转换为Number, 得到 0==0
        - 所以, 答案是 true !
    Copy after login
  3. 如何使a==1 && a==2 && a==3的结果为 true

    var a = {
        value: 0,
        valueOf: function() {
            this.value += 1;
            return this.value    }};console.log(a == 1 && a == 2 && a == 3) // true
    Copy after login
  4. 如何使a===1&&a===2&&a===3的结果为 true

    // 使用 defineProperty 进行数据劫持var value = 0;Object.defineProperty(window,"a",{
        get(){
            return ++value;
        }})console.log(a===1&&a===2&&a===3)  //true
    Copy after login
  5. 实现一个无限累加函数

  6. 柯里化实现多参累加

相关推荐:javascript学习教程

The above is the detailed content of JavaScript skills: unboxing and type conversion. 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)

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