Table of Contents
STRANGER THINGS
When a number becomes a string
What is the meaning of [object Object] in JavaScript?
等于还是不等于?
Home Web Front-end JS Tutorial Introduction to forced type conversion in JavaScript

Introduction to forced type conversion in JavaScript

Apr 12, 2019 am 10:55 AM
javascript front end type conversion

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;
Copy after login
Copy after login

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;
Copy after login

Then comes undefined, which means the variable is still not attached:

var name;
console.log(name)
undefined
Copy after login

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"
Copy after login

and numbers:

typeof 9
> "number"
Copy after login

For booleans:

typeof false
> "boolean"
Copy after login

undefined:

typeof undefined
> "undefined"
Copy after login

and null :

typeof null
> "object"
Copy after login

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
Copy after login
Copy after login
Copy after login

will give you a clear error:

TypeError: can only concatenate str (**not** "int") to str
Copy after login

In JavaScript, the sky is the limit:

'hello' + 89
Copy after login
Copy after login
Copy after login

Facts Given above:

"hello89"
Copy after login
Copy after login

If we try to add an array to a string, it will look even weirder:

'hello' + []
Copy after login

will get

1. 'hello'
Copy after login

and

1. 'hello' + [89]
Copy after login

Will give you a surprise:

1. "hello89"
Copy after login

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']
Copy after login

Get:

1. "hello89,150.156,mike"
Copy after login

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;
Copy after login
Copy after login

If I want to explicitly convert, I can express the intention in the code:

var greet = "Hello";
var year = 89;

var yearString = year.toString()
Copy after login

Or do this:

var greet = "Hello";
var year = 89;

var yearString = String(year)
Copy after login

Then I can concatenate the two Variables:

greet + yearString;
Copy after login

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
Copy after login
Copy after login
Copy after login

would get:

"hello89"
Copy after login
Copy after login

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']
Copy after login

will get:

"hello89,150.156,mike"
Copy after login

So what will the following code get:

'hello' + { name: "Jacopo" }
Copy after login

To find out, you can do a quick test by converting the object to a string:

String({ name: "Jacopo" })
Copy after login

will get:

"[object Object]"
Copy after login

So I have a feeling:

1. 'hello' + { name: "Jacopo" }
Copy after login

will Got:

1. "hello[object Object]"
Copy after login

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
Copy after login

看上去一切都还好。

现在尝试比较两种不同的类型,数字和字符串。首先是“强比较”:

1. "1" === 1
2. false
Copy after login

这说得通!字符串“1”与数字1是不同的。但是“弱比较”会发生什么?

1. "1" == 1
2. true
Copy after login

居然是true!它没有任何意义,除非这种行为与我们之前看到的隐式转换有关。

如果适用相同的规则怎么办?没错! ECMAScript spec 再次罢工。结果抽象比较运算符在比较它们之前在类型之间进行自动转换。这是规范的摘要:

比较 x == y 执行如下:

如果 x 是 String 且 y 是Number,则返回比较结果 ToNumber(x)== y

规范说:如果第一个操作数是一个字符串,第二个操作数是一个数字,那么将第一个操作数转换为数字。有趣。

JavaScript 规范充满了这个疯狂的规则,我强烈鼓励大家对它深入挖掘。

在此期间除非你有充分的理由否则在 JavaScript 代码中避免使用抽象比较运算符。你以后会感谢自己的。

那么“强势比较”怎么样?规范中的说 严格相等比较在把值与三等 === 进行比较之前没有进行自动转换。在代码中使用严格相等比较可以避免愚蠢的 bug。

总结

JavaScript 中有七个构建块,即 StringNumberBooleanNullUndefinedObjectSymbol。这些类型被称为基元

JavaScript 开发人员可以使用算术和比较运算符来操作这些类型。但是我们要特别注意加法运算符 +抽象比较运算符 ==,它本质上倾向于在类型之间进行转换。

JavaScript 中的隐式转换称为强制类型转换,并在 ECMAScript 规范中定义。无论什么时候你的代码都要使用严格的比较运算符 === 而不是 ==

作为最佳实践,当你打算在两种类型之间进行转换时,请务必明确操作。JavaScript 有一堆内置对象,它们反映了原始类型:StringNumberBoolean。这些内置类型可用于在不同类型之间进行显式转换。

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!

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
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

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

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

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.

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.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

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.

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,

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

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: explore how Golang plays a role in the front-end field Combination of Golang and front-end technology: explore how Golang plays a role in the front-end field Mar 19, 2024 pm 06:15 PM

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

See all articles