Let's discuss the pitfalls of 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'); }
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
The above order is arranged according to the basic types.
Nothing else! ! Even if it is in the following form:
Infinity '0'、'false'、" "(空格字符) 任何引用类型:[],{},function(){}
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"
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
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.其他报错。
Convert reference type to number
1.优先调用valueOf方法(如果有),看其返回结果是否是基本类型,如果是,转化为数字,返回。 2.否则,调用toString方法(如果有),看其返回结果是否是基本类型,如果是,转化为数字,返回。 3.其他报错。
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()); // 对象本身
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
Another error situation:
var a = {}; a.toString = function() {return {};} console.log("" + a); // 报错 console.log(+a) // 报错
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'); }
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,其余都不相等。
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
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)
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.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



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

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 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

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

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.

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: 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.

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.
