Home >Web Front-end >JS Tutorial >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:
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.
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.
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?
"[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!