Introduction to forced type conversion in JavaScript
Apr 12, 2019 am 10:55 AMThis 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).
但是當(dāng)你在普通的 JavaScript 對(duì)象上調(diào)用 toString()
時(shí),引擎會(huì)給出“[object Object]”,因?yàn)?Object.toString()
的默認(rèn)行為是由實(shí)體類型(在這種情況下為Object)返回字符串 object 。
現(xiàn)在讓我們把注意力集中在 JavaScript 比較運(yùn)算符上,它們與算術(shù)運(yùn)算符一樣奇怪。
等于還是不等于?
JavaScript 中有兩個(gè)主要的比較運(yùn)算符。
第一個(gè)我們稱之為“弱比較”。這是抽象比較運(yùn)算符(雙等號(hào)):==
。
另一個(gè)是“強(qiáng)比較”,可以通過(guò)三等號(hào)進(jìn)行識(shí)別:===
也稱為嚴(yán)格比較運(yùn)算符。它們兩者的行為方式完全不同。
來(lái)看一些例子。首先,如果我們將兩個(gè)字符串與兩個(gè)運(yùn)算符進(jìn)行比較,我們得到相同的結(jié)果
"hello"?==?"hello" >?true "hello"?===?"hello" >?true
看上去一切都還好。
現(xiàn)在嘗試比較兩種不同的類型,數(shù)字和字符串。首先是“強(qiáng)比較”:
1.?"1"?===?1 2.?false
這說(shuō)得通!字符串“1”與數(shù)字1是不同的。但是“弱比較”會(huì)發(fā)生什么?
1.?"1"?==?1 2.?true
居然是true!它沒(méi)有任何意義,除非這種行為與我們之前看到的隱式轉(zhuǎn)換有關(guān)。
如果適用相同的規(guī)則怎么辦?沒(méi)錯(cuò)! ECMAScript spec 再次罷工。結(jié)果抽象比較運(yùn)算符在比較它們之前在類型之間進(jìn)行自動(dòng)轉(zhuǎn)換。這是規(guī)范的摘要:
比較 x == y 執(zhí)行如下:如果 x 是 String 且 y 是Number,則返回比較結(jié)果 ToNumber(x)== y
規(guī)范說(shuō):如果第一個(gè)操作數(shù)是一個(gè)字符串,第二個(gè)操作數(shù)是一個(gè)數(shù)字,那么將第一個(gè)操作數(shù)轉(zhuǎn)換為數(shù)字。有趣。
JavaScript 規(guī)范充滿了這個(gè)瘋狂的規(guī)則,我強(qiáng)烈鼓勵(lì)大家對(duì)它深入挖掘。
在此期間除非你有充分的理由否則在 JavaScript 代碼中避免使用抽象比較運(yùn)算符。你以后會(huì)感謝自己的。
那么“強(qiáng)勢(shì)比較”怎么樣?規(guī)范中的說(shuō) 嚴(yán)格相等比較在把值與三等 ===
進(jìn)行比較之前沒(méi)有進(jìn)行自動(dòng)轉(zhuǎn)換。在代碼中使用嚴(yán)格相等比較可以避免愚蠢的 bug。
總結(jié)
JavaScript 中有七個(gè)構(gòu)建塊,即 String,Number,Boolean,Null,Undefined,Object 和 Symbol。這些類型被稱為基元。
JavaScript 開(kāi)發(fā)人員可以使用算術(shù)和比較運(yùn)算符來(lái)操作這些類型。但是我們要特別注意加法運(yùn)算符 +
和抽象比較運(yùn)算符 ==
,它本質(zhì)上傾向于在類型之間進(jìn)行轉(zhuǎn)換。
JavaScript 中的隱式轉(zhuǎn)換稱為強(qiáng)制類型轉(zhuǎn)換,并在 ECMAScript 規(guī)范中定義。無(wú)論什么時(shí)候你的代碼都要使用嚴(yán)格的比較運(yùn)算符 ===
而不是 ==
。
作為最佳實(shí)踐,當(dāng)你打算在兩種類型之間進(jìn)行轉(zhuǎn)換時(shí),請(qǐng)務(wù)必明確操作。JavaScript 有一堆內(nèi)置對(duì)象,它們反映了原始類型:String
,Number
,Boolean
。這些內(nèi)置類型可用于在不同類型之間進(jìn)行顯式轉(zhuǎn)換。
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

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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

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

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.

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.

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

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

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of ??componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.
