Home Web Front-end JS Tutorial Let's discuss the pitfalls of JS type conversion

Let's discuss the pitfalls of JS type conversion

Jan 23, 2017 pm 02:18 PM
js type conversion

Why do you want to say this?
An interview question gives me the motivation for talking about it.
The question is as follows:

var bool = new Boolean(false);
if (bool) {
    alert('true');
} else {
    alert('false');
}
Copy after login

The running result is true! ! !
Actually, type conversion, operator priority, these things are the most basic.
There is a detailed introduction in the rhinoceros book. But I rarely read the first 5 chapters of the Rhino book. . .
For example, regarding priorities, many books teach us, "There is no need to memorize the priority order. If you are not sure, just add parentheses."
We usually do this when writing code.
But what is the reality? This kind of question will be asked during the interview and you will be asked to answer it. . .
I really don’t know the meaning of this kind of question. . .
The complaints stop here. This article attempts to solve the type conversion problem and try to memorize the table on page 49 of the "JS Authoritative Guide".
What are the false values?
6 in total:

0或+0、-0,NaN
""
false
undefined
null
Copy after login

The above order is arranged according to the basic types.
Nothing else! ! Even if it is in the following form:

Infinity
'0'、'false'、" "(空格字符)
任何引用类型:[],{},function(){}
Copy after login

The correct way to understand if (a && b) is: a && b evaluates the expression and then converts it to the Boolean type.
&& is a short-circuit syntax. After evaluation, it is not necessarily a Boolean type, nor is it converted into Boolean values ​​on both sides and then operated.
For example, the result of 2&&3 is 3, not true.
So if(a && b), what we usually understand, "if a and b are true at the same time", is a wrong way of describing it.
Convert other basic types to strings, which is basically the same as expected:

console.log("" + null);      // "null"
console.log("" + undefined); // "undefined"
console.log("" + false);     // "false"
console.log("" + true);      // "true"
console.log("" + 0);         // "0"
console.log("" + NaN);       // "NaN"
console.log("" + Infinity);  // "Infinity"
Copy after login

Convert other basic types to numbers, which requires special memory:

console.log(+null);          // 0
console.log(+undefined);     // NaN
console.log(+false);         // 0
console.log(+true);          // 1
console.log(+"");            // 0
console.log(+'1');           // 1
console.log(+'1x');          // NaN
Copy after login

Where null, the empty character is 0, and undefined is NaN.
Above, the basic type conversions are explained clearly.

Let’s take a look at converting reference types into basic types.
Convert reference type to boolean, always true
Convert reference type to string

1.优先调用toString方法(如果有),看其返回结果是否是原始类型,如果是,转化为字符串,返回。
2.否则,调用valueOf方法(如果有),看其返回结果是否是原始类型,如果是,转化为字符串,返回。
3.其他报错。
Copy after login

Convert reference type to number

1.优先调用valueOf方法(如果有),看其返回结果是否是基本类型,如果是,转化为数字,返回。
2.否则,调用toString方法(如果有),看其返回结果是否是基本类型,如果是,转化为数字,返回。
3.其他报错。
Copy after login

First let’s look at what common reference types toString and valueOf return?

var a = {};
console.dir(a.toString());   // "[object Object]"
console.dir(a.valueOf());    // 对象本身
 
var b = [1, 2, 3];
console.dir(b.toString());   // "1,2,3"
console.dir(b.valueOf());    // 对象本身
 
var c = [[1],[2]];
console.dir(c.toString());   // "1,2"
console.dir(c.valueOf());    // 对象本身
 
var d = function() {return 2};
console.dir(d.toString());   // "function() {return 2}"
console.dir(d.valueOf());    // 对象本身
Copy after login

So the corresponding conversion to strings and numbers is:

var a = {};
console.dir(a + "");         // "[object Object]"
console.dir(+a);             // NaN
 
var b = [1, 2, 3];
console.dir(b + "");         // "1,2,3"
console.dir(+b);             // NaN
 
var c = [[1],[2]];
console.dir(c + "");         // "1,2"
console.dir(+c);             // NaN
 
var d = function() {return 2};
console.dir(d + "");         // "function () {return 2}"
console.dir(+d);             // NaN
Copy after login

Another error situation:

var a = {};
a.toString = function() {return {};}
console.log("" + a);         // 报错
console.log(+a)              // 报错
Copy after login

The above type conversion rules are basically finished.

Finally, let’s talk about the evil “==”
The interview questions are as follows:

var a = false;
var b = undefined;
if (a == b) {
    alert('true');
} else {
    alert('false');
}
Copy after login

I thought true would pop up. Oh my God! Why is it false?
Haha. . .
Double equal sign, if the types of both sides are different, implicit conversion will occur. Rhino book page 75 summarizes it as follows:

1,null和undefined,相等。
2,数字和字符串,转化为数字再比较。
3,如果有true或false,转换为1或0,再比较。
4,如果有引用类型,优先调用valueOf。
5,其余都不相等。
Copy after login

Therefore:

console.log(undefined == false); // false
console.log(null == false);      // false
console.log(0 == false);         // true
console.log(NaN == false);       // false
console.log("" == false);        // true
Copy after login

0 == false The reason why it is true is based on item 3.
The reason why "" == false is true according to Article 3 becomes "" == 0, and then according to Article 2.
Another example from Article 4:

console.log([[2]] == 2)
Copy after login

The above result is true for the following reasons:
[[2]]'s valueOf is the object itself, not the basic type.
The result of trying to call toString is '2'.
So it becomes a comparison of '2' and the number 2. According to Article 2, equal. WTF!!
Finally, using "===" will eliminate these problems.
End of this article.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Type conversion of golang function Type conversion of golang function Apr 19, 2024 pm 05:33 PM

In-function type conversion allows data of one type to be converted to another type, thereby extending the functionality of the function. Use syntax: type_name:=variable.(type). For example, you can use the strconv.Atoi function to convert a string to a number and handle errors if the conversion fails.

Implicit type conversion: An exploration of different variations of types and their applications in programming Implicit type conversion: An exploration of different variations of types and their applications in programming Jan 13, 2024 pm 02:54 PM

Explore the different types of implicit type conversions and their role in programming Introduction: In programming, we often need to deal with different types of data. Sometimes, we need to convert one data type to another type in order to perform a specific operation or meet specific requirements. In this process, implicit type conversion is a very important concept. Implicit type conversion refers to the process in which the programming language automatically performs data type conversion without explicitly specifying the conversion type. This article will explore the different types of implicit type conversions and their role in programming,

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Can Golang function return values ​​be cast? Can Golang function return values ​​be cast? Apr 13, 2024 am 11:36 AM

Go language allows function return value coercion, and its syntax format is value:=variable.(targetType). Casting can be used to convert a value of type interface{} to a specific type, such as map[string]string. Considerations include type compatibility, value validation, and careful use.

See all articles