当前位置:网站首页>Explain in detail the addition (+) operation in JS, basic data type addition, reference data type addition, and the underlying operation rules, [] + {}, {} + []
Explain in detail the addition (+) operation in JS, basic data type addition, reference data type addition, and the underlying operation rules, [] + {}, {} + []
2022-07-25 23:04:00 【Small front end in the process of being lost】
Let's do some simple calculation problems first :
Calculation questions :
{} + []
[] + {}
1 + true
1 + false
Do you think it's very simple , Yes , If you have a good foundation , You will feel that it is really quite simple . If you are not sure about your answer , take it easy , I will explain these questions to you in detail later , And will say why it is like this .
Don't say much. Let's show you the answer first
console.log({
}+[]);//[object Object]
console.log([]+{
});//[object Object]
console.log(1 + true);//2
console.log(1 + false);//1
The first question : Add an array and an object , The answer returned is [object Object], Actually in JavaScript in , Reference data types cannot be added , The values on both sides of the plus sign must be converted into basic data types , Then add . How to convert the values of these two reference data types into basic data types ?
Follow the steps below , You can reference data types , Convert to basic data type
1. Judge whether the left side is the basic data type , If so , That's the end of the step , If not , Perform the following steps
2. call valueOf Method , If the return value is the basic data type , That's the end of the step , If not , Perform the following steps
3. call toString Method , If the basic data type is returned , That's the end of the step , If not , Report errors
Follow the steps above , Let's practice this problem , On the left is {}, At first glance, it is not a basic data type , Execution steps 2, call valueOf, What is returned is the object itself {}, After detection, it is not a basic data type , Then follow the steps 3, call toString Method , Return string [object Object], Judge whether the string is the basic data type , End all steps .
On the right is an empty array [], Still follow the steps , First call valueOf, An empty string is returned , Judge whether this empty string is the basic data type , End step
Both left and right sides are converted to basic data types , You can add it up , Empty string and [object Object] Add up , Of course [object Object] String .
The second question : If you read the analysis of the first question , There is no need to talk about the second question , Basically as like as two peas , But why do we have two same questions , The reason is to confuse your eyes , Written examination questions often give such questions , In fact, the result is the same .
The third question :1 + true, The number on the left 1 It's the basic data type , On the right Boolean type true, It's all basic data types , So the above method is completely unnecessary , Logically speaking, it can be added directly , But how to add ? because JavaScript It's a weakly typed language , Just don't check the type , But though js Is a weakly typed language that does not type check , This does not mean that the two data types can be added . So let's say , Numeric types and Boolean types cannot be added , Then why did you return to this problem 2 Well , In fact, there is still a step in addition , That is implicit type conversion . All and Number The value of type addition will be converted to Number, In this question ,true It's converted into numbers 1, So the return is 2.
The fourth question :1 + false, Same as the third question ,false Implicitly converted to 0,1+0 The data returned is 1 了 .
The knowledge points of these questions :
1. Basic data types and reference data types
The basic data types are :string, number, boolean, null, undefined, symbol, bigint
Reference data type :Object
Basic data types are also called primitive data types , What is the primitive type? The latter refers to the basic type ?
except Object All other types are immutable ( Value itself cannot be changed ). for example , And C Different language ,JavaScript The string in is immutable ( Translation notes : Such as ,JavaScript The string operation in must return a new string , The original string has not been changed ). We call these types of values “ Original value ”.
2. Implicit conversion rules for basic data types
For everyone to remember more easily , We classify here , Here, it is simply divided into three categories .
2.1 character string + Other original types
Remember a word , No matter who adds it to the string , All need to be converted into basic data type strings

2.2 Numbers + Other non string raw data types
Number The priority of is a little lower than the string , Whatever the data type ( Except for Strings ), And Number If the values of types are added , All need to be converted into Number type

It can be seen here Boolean Type of true convert to 1,false convert to 0,null convert to 0,undefined convert to NaN( That is to say not a number Abbreviation )
2.3 Numbers / Add raw data types other than strings
When numbers and other raw data types other than strings use the plus sign operation directly , It is to convert to numbers and then calculate , This has nothing to do with strings

3. How to convert a reference data type into a basic data type (ToPrimitive Conversion algorithm )
ToPrimitive(input, PreferredType) Algorithm :
ToPrimitive The function of the algorithm is to convert the value into the original value , The method called internally is value Methods and toString Method to convert
General conversion steps :
1. If input It's the original value , Return this value ( There is nothing else to do ).
2. otherwise , If input It's the object , call input.valueOf(). If the result is the original value , Returns the result .
3. otherwise , call input.toString() . If the result is the original value , Return results .
4. otherwise , Throw a TypeError ( Description error converting input to original value ).
PreferredType yes String
take Number The second and third steps in the conversion step of .
PreferredType It can also be omitted
In this case , The date will be considered String Other values will be considered Number , therefore + Operators and == Operators can operate ToPrimitive().
4.toString Method ,valueOf Method
First MDN The official link offers , It's written in detail here , Look at these two documents , You will understand everything . Of course, I will briefly summarize it below .
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
toString:
**toString()** Method returns a string representing the object .
because toString The method is Object The prototype method above , because JavaScript It is inherited through the prototype chain , And all objects inherit from Object So other objects inherit Object Of toString Method , But some built-in object pairs toString Method is overridden
Every object has one toString() Method , When the object is represented as a text value , Or an object is automatically called when it is referenced in the expected string way . By default ,toString() The method is each Object Object inheritance . If this method is not overridden in the custom object ,toString() return “[object type]”, among type It's the type of object . The following code illustrates this :
var o = new Object();
o.toString(); // returns [object Object]
valueOf:
**valueOf()** Method returns the original value of the specified object .
describe :
JavaScript call valueOf Method to convert the object to the original value . You rarely have to call it yourself valueOf Method ; When you encounter an object with the original value you want to expect ,JavaScript It will be called automatically .
By default ,valueOf Method by Object After each inherited object . Each built-in core object will override this method to return the appropriate value . If the object has no original value , be valueOf The object itself is returned .
JavaScript Many of our built-in objects override this function , In order to achieve more suitable for their own functional needs . therefore , Different types of objects valueOf() Methods may have different return values and return value types .
| object | Return value |
|---|---|
| Array | Returns the array object itself . |
| Boolean | Boolean value . |
| Date | The stored time is from 1970 year 1 month 1 The number of milliseconds from midnight UTC. |
| Function | The function itself . |
| Number | Numerical value . |
| Object | Object itself . This is the default . |
| String | A string value . |
| Math and Error Objects have no valueOf Method . |
边栏推荐
- BIO、NIO、AIO的区别?
- CUDA environment construction
- Network Security Learning (XV) ARP
- CMU AI PhD first year summary
- Enabling partners, how can Amazon cloud technology "get on the horse and get a ride"?
- The fourth experiment nat
- Node.js operation database
- Anaconda~Upload did not complete.
- 【论文笔记】A Meta-Reinforcement Learning Algorithm for Causal Discovery
- Analysis of direction finding error of multi baseline interferometer system
猜你喜欢

QT Chinese programming encounters c2001 error, prompting "there is a newline character in the constant"

Analysis of the influence of ESM direction finding error on positioning error

Take root downward, grow upward, and explore the "root" power of Huawei cloud AI

Madness. Smbms (supermarket order management system)

IPFs of Internet Protocol

Sichuan cuisine menu (I)

Recyclerview computehorizontalscrollextend computehorizontalscrollrange computehorizontalscroll for calculating the sliding distance

通用分页功能

Opencv compile and call GPU version
![[interface performance optimization] reasons for index failure and how to optimize SQL](/img/b9/64058c823c4497ac36bfb62a101816.jpg)
[interface performance optimization] reasons for index failure and how to optimize SQL
随机推荐
Understanding of forward proxy and reverse proxy
自定义mvc原理
【PMP学习笔记】第1章 PMP体系引论
access-list vs ip access-list
What are the differences between FileInputStream and bufferedinputstream?
BIO、NIO、AIO的区别?
Network Security Learning (XV) ARP
7-1 understand everything
Websocket summary
[literature reading] - HRL -[hrl with universal policies for multi step robotic control]
Redis过期键的删除策略[通俗易懂]
Enabling partners, how can Amazon cloud technology "get on the horse and get a ride"?
invalid syntax
Zcmu--5015: complete the task
CUDA environment construction
第二周学习:卷积神经网络
单模型常识推理首超人类!HFL登顶OpenBookQA挑战赛
[PTA] 7-19 check face value (15 points)
How to obtain the cash flow data of advertising services to help analyze the advertising effect?
Deploy flash based websites using Google cloud