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.

Related recommendations: javascript tutorial
Basic data types: string, number, boolean
Reference type: object, function
Non-existing type: undefined
String,Number,Booleanbelong tostring,number respectively,booleanare 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);
The execution steps of the second line above are actually as follows:
- Use
new String('Hello World')Create a temporary instance object; - Use the temporary object to call the
substringmethod; - 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);
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
-
If both ends of the arithmetic operator are data of type
number, the calculation is performed directly; If there are non-
numberbasic data types at both ends of the arithmetic operator, useNumber()# for the non-numberoperands. ##Carry out boxing, and then unbox the return value into thenumbertype to participate in the calculation;- 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 toCondition 2, otherwiseCondition 1will be executed.
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
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`的拆箱操作再变成数字 5String connectorThe 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
- string
, connect directlyIf there are non- - string# at both ends of the operator ## basic type, use
String()to box non-stringbasic type data, and then unbox the return value into a basic type to participate in string splicing.When - there are reference data types at both ends, the reference type will be unboxed first. If the result is not a
stringtype, then the reference type will be unboxed according toCondition 2is executed, otherwisecondition 1is executed. Relational operator
- #NaN
and any other type, any relational operation will always return
false( including himself). If you want to determine whether a variable isNaN, you can useNumber.isNaN()to determine. - null == undefined
The comparison result is
This is defined by the rules,true, in addition,null,undefined The comparison value betweenand any other result (excluding themselves) isfalse.null
is the type of object, but there will be syntax errors when calling
valueOfortoString, here Just remember the result. generally: - 如果算术运算符两端均为
number类型的数据,直接进行计算; - 如果算术运算符两端存在非
number的基本数据类型,则对非number的运算数使用Number()进行装箱,然后对返回值进行拆箱为number类型,参与计算; - 算术运算符两端存在引用数据类型,则先对引用类型进行拆箱操作,如果结果为非
number类型,则根据条件2执行,否则执行条件1。
- 如果算术运算符两端均为
{} == !{}
// false Number({}.valueOf().toString())==> NaN , 所以题目等同于 NaN == false , NaN 和 任何类型比较都是 false[] == []
// false 内存地址不同![] == 0
// true ![]==>false , 所以题目等同于 false==0 , Number(false)==>0 , 所以结果为 true
一些题目
-
[] == ![]- 第一步,![] 会变成 false - 第二步,[]的valueOf是[],[]是引用类型,继续调用toString,题目变成: "" == false - 第三步,符号两端转换为Number, 得到 0==0 - 所以, 答案是 true
-
[undefined] == false- 第一步,[undefined]的valueOf结果为 [undefined],然后[undefined]通过toString变成 '' ,所以题目变成 '' == false - 第二步,符号两端转换为Number, 得到 0==0 - 所以, 答案是 true !
-
如何使
a==1 && a==2 && a==3的结果为truevar a = { value: 0, valueOf: function() { this.value += 1; return this.value }};console.log(a == 1 && a == 2 && a == 3) // true -
如何使
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 实现一个无限累加函数
柯里化实现多参累加
相关推荐: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!
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.
Demystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AMJavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)







