Introduction to forced type conversion in JavaScript
This article brings you an introduction to the method of forced type conversion in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
JavaScript Primitives
JavaScript is built on a series of basic units. Some of them should already be familiar to you, such as strings and numbers:
var greet = "Hello"; var year = 89;
Strings and numbers are part of the so-called primitives of the language. The full list is:
- String
- Number
- Boolean
- Null
- Undefined
- Object
- Symbol (Added in ES6, not introduced here)
Boolean values are used to represent values that may be true or false. null is intentionally not assigned. It is usually assigned to a variable to indicate that the binding is complete and will be filled with meaningful content later.
var maybe = null;
Then comes undefined, which means the variable is still not attached:
var name; console.log(name) undefined
null and undefined look very similar, but they are two completely different things entities, many developers are still unsure which one to use.
If you want to determine the type of a JavaScript instance, you can use the typeof
operator. Let’s try it with strings:
typeof "alex" > "string"
and numbers:
typeof 9 > "number"
For booleans:
typeof false > "boolean"
undefined:
typeof undefined > "undefined"
and null :
typeof null > "object"
The results are surprising! null looks like an object, but it's actually a historical bug in JavaScript that's been there since the language was born. Due to these problems, JavaScript has always had a bad reputation. But this is just the beginning.
STRANGER THINGS
In JavaScript, there are some strange rules when converting between two types. Let me give you some background information. Let’s give an example using Python first. Executing the following command in Python:
'hello' + 89
will give you a clear error:
TypeError: can only concatenate str (**not** "int") to str
In JavaScript, the sky is the limit:
'hello' + 89
Facts Given above:
"hello89"
If we try to add an array to a string, it will look even weirder:
'hello' + []
will get
1. 'hello'
and
1. 'hello' + [89]
Will give you a surprise:
1. "hello89"
Looks like there is some logic behind this conversion. It even works for arrays where more elements are present:
1. 'hello' + [89, 150.156, 'mike']
Get:
1. "hello89,150.156,mike"
These two lines of JavaScript are enough to make Java programmers run away. But this behavior 100% makes sense in JavaScript. Therefore, this implicit conversion, also known as forced type conversion, is very worth exploring.
When a number becomes a string
Some programming languages have a concept called Type conversion, which means: If I want to convert a number or instance to another type, then I have to make an explicit conversion to . It also works with JavaScript. See the following example:
var greet = "Hello"; var year = 89;
If I want to explicitly convert, I can express the intention in the code:
var greet = "Hello"; var year = 89; var yearString = year.toString()
Or do this:
var greet = "Hello"; var year = 89; var yearString = String(year)
Then I can concatenate the two Variables:
greet + yearString;
But in JavaScript there is a subtle mechanism called implicit conversion, which is provided by the JavaScript engine. The language doesn't prevent us from adding numbers and strings:
'hello' + 89
would get:
"hello89"
But what's the logic behind this conversion? You may be surprised to learn that the addition operator
in JavaScript will automatically convert either of its two operands to a string if at least one of them is For strings!
You will find that what is even more surprising is that this rule is consistent in the ECMAScript specification. Section 11.6.1 defines the behavior of the addition operator, and I've summarized it for you here:
If x is a String or y is a String, return ToString(x), then return ToString(y)
Does this trick only work with numbers? Not really. Arrays and objects will also be subject to the same conversion:
'hello' + [89, 150.156, 'mike']
will get:
"hello89,150.156,mike"
So what will the following code get:
'hello' + { name: "Jacopo" }
To find out, you can do a quick test by converting the object to a string:
String({ name: "Jacopo" })
will get:
"[object Object]"
So I have a feeling:
1. 'hello' + { name: "Jacopo" }
will Got:
1. "hello[object Object]"
Stop it! What is this?
What is the meaning of [object Object] in JavaScript?
"[object Object]" is one of the most common JavaScript "quirks".
Almost every JavaScript instance has a method named toString()
, and some methods are provided by Object.prototype.toString
.
Some types, such as arrays, implement a custom version of toString()
to convert the value to a string when the method is called. For example Array.prototype.toString
will override Object.toString()
(also known as method shadowing).
但是当你在普通的 JavaScript 对象上调用 toString()
时,引擎会给出“[object Object]”,因为 Object.toString()
的默认行为是由实体类型(在这种情况下为Object)返回字符串 object 。
现在让我们把注意力集中在 JavaScript 比较运算符上,它们与算术运算符一样奇怪。
等于还是不等于?
JavaScript 中有两个主要的比较运算符。
第一个我们称之为“弱比较”。这是抽象比较运算符(双等号):==
。
另一个是“强比较”,可以通过三等号进行识别:===
也称为严格比较运算符。它们两者的行为方式完全不同。
来看一些例子。首先,如果我们将两个字符串与两个运算符进行比较,我们得到相同的结果
"hello" == "hello" > true "hello" === "hello" > true
看上去一切都还好。
现在尝试比较两种不同的类型,数字和字符串。首先是“强比较”:
1. "1" === 1 2. false
这说得通!字符串“1”与数字1是不同的。但是“弱比较”会发生什么?
1. "1" == 1 2. true
居然是true!它没有任何意义,除非这种行为与我们之前看到的隐式转换有关。
如果适用相同的规则怎么办?没错! ECMAScript spec 再次罢工。结果抽象比较运算符在比较它们之前在类型之间进行自动转换。这是规范的摘要:
比较 x == y 执行如下:如果 x 是 String 且 y 是Number,则返回比较结果 ToNumber(x)== y
规范说:如果第一个操作数是一个字符串,第二个操作数是一个数字,那么将第一个操作数转换为数字。有趣。
JavaScript 规范充满了这个疯狂的规则,我强烈鼓励大家对它深入挖掘。
在此期间除非你有充分的理由否则在 JavaScript 代码中避免使用抽象比较运算符。你以后会感谢自己的。
那么“强势比较”怎么样?规范中的说 严格相等比较在把值与三等 ===
进行比较之前没有进行自动转换。在代码中使用严格相等比较可以避免愚蠢的 bug。
总结
JavaScript 中有七个构建块,即 String,Number,Boolean,Null,Undefined,Object 和 Symbol。这些类型被称为基元。
JavaScript 开发人员可以使用算术和比较运算符来操作这些类型。但是我们要特别注意加法运算符 +
和抽象比较运算符 ==
,它本质上倾向于在类型之间进行转换。
JavaScript 中的隐式转换称为强制类型转换,并在 ECMAScript 规范中定义。无论什么时候你的代码都要使用严格的比较运算符 ===
而不是 ==
。
作为最佳实践,当你打算在两种类型之间进行转换时,请务必明确操作。JavaScript 有一堆内置对象,它们反映了原始类型:String
,Number
,Boolean
。这些内置类型可用于在不同类型之间进行显式转换。
The above is the detailed content of Introduction to forced type conversion in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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



PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

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.

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

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

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,

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn
