Javascript 中的类型强制到底是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19915688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What exactly is Type Coercion in Javascript?
提问by gespinha
What exactly is type coercion in Javascript?
Javascript 中的类型强制究竟是什么?
For example, on the use of ==
instead of ===
?
例如,使用 of==
而不是===
?
回答by Barmar
Type coercion means that when the operands of an operator are different types, one of them will be converted to an "equivalent" value of the other operand's type. For instance, if you do:
类型强制意味着当一个运算符的操作数是不同类型时,其中一个将转换为另一个操作数类型的“等效”值。例如,如果你这样做:
boolean == integer
the boolean operand will be converted to an integer: false
becomes 0
, true
becomes 1. Then the two values are compared.
布尔操作数将转换为整数:false
变成0
,true
变成 1。然后比较两个值。
However, if you use the non-converting comparison operator ===
, no such conversion occurs. When the operands are of different types, this operator returns false
, and only compares the values when they're of the same type.
但是,如果您使用非转换比较运算符===
,则不会发生此类转换。当操作数的类型不同时,此运算符返回false
,并且仅比较相同类型的值。
回答by linstantnoodles
Let's start with a short intro to type systems which I think will help you understand the general idea of type coercion.
让我们从对类型系统的简短介绍开始,我认为这将有助于您理解类型强制的一般概念。
The type system of a language defines rules that tell us what types of data exist in that language and how they can be combined using different operators. For example, one such rule might specify that the plus (+) operator only acts on numbers. These rules exist primarily to prevent you from shooting yourself in the foot. But what happens when the programmer breaks that rule in the program? There's nothing preventing the programmer from typing {} + {}
or “hello” + 5
in a program even if the language doesn't think those expressions make any sense.
语言的类型系统定义了规则,这些规则告诉我们该语言中存在哪些类型的数据以及如何使用不同的运算符组合它们。例如,一个这样的规则可能指定加号 (+) 运算符仅作用于数字。这些规则的存在主要是为了防止您用脚射击。但是当程序员在程序中打破这个规则时会发生什么?即使语言认为这些表达式没有任何意义,也没有什么可以阻止程序员输入{} + {}
或输入“hello” + 5
程序。
What ultimately happens in those situations depends on how strict the language is about its type rules.
在这些情况下最终会发生什么取决于语言对其类型规则的严格程度。
A languages type system often holds one of two positions about you breaking its rules:
语言类型系统通常会持有关于你违反规则的两种立场之一:
- Say “Hey, that's not cool!” and immediately crash your program.
- Say “I can't do anything with {} … but I can do something with numbers” and attempt to convert {} to a number.
- 说“嘿,这不酷!” 并立即使您的程序崩溃。
- 说“我不能用 {} 做任何事情……但我可以用数字做某事”并尝试将 {} 转换为数字。
Languages with type systems that take the first position about its rules are colloquially referred to as “strongly typed” languages. They are strict about not letting you break its rules. Those that take the second approach (such as JavaScript) are referred to as “weakly typed” or “loosely typed” languages. Sure, you can break the rules, but don't be surprised when it converts the type of data you described in your program by force in order to comply with its rules. That behavior is known as … (drum roll) ... type coercion.
类型系统在其规则方面占据首位的语言通俗地称为“强类型”语言。他们严格要求不让您违反规则。那些采用第二种方法(例如 JavaScript)的语言被称为“弱类型”或“松散类型”语言。当然,您可以违反规则,但是当它强制转换您在程序中描述的数据类型以符合其规则时,请不要感到惊讶。这种行为被称为……(鼓声)……类型强制。
Now let's look at some examples in JavaScript. First, let's start with an expression that does not lead to type coercion.
现在让我们看一些 JavaScript 的例子。首先,让我们从一个不会导致类型强制的表达式开始。
5 + 5
Using the + operator with two numbers which is perfectly valid. The program will treat + to mean “add” and happily add the two numbers. No conversion necessary.
对两个数字使用 + 运算符,这是完全有效的。程序会将 + 视为“相加”并愉快地将两个数字相加。无需转换。
But what about …
但是关于 …
[] + 5
Uh oh. In JavaScript, +
can mean add two numbers or concatenate two strings. In this case, we have neither two numbers nor two strings. We only have one number and an object. According to JavaScript's type rules, this makes no logical sense. Since it's forgiving about you breaking its rules, instead of crashing it tries to make sense of it anyway. So what does JavaScript do? Well, it knows how to concatenate strings, so it converts both [] and 5 into strings and the result is string value “5”.
哦哦。在 JavaScript 中,+
可以表示添加两个数字或连接两个字符串。在这种情况下,我们既没有两个数字也没有两个字符串。我们只有一个数字和一个对象。根据 JavaScript 的类型规则,这没有逻辑意义。因为它原谅你违反它的规则,而不是崩溃它无论如何都会试图理解它。那么 JavaScript 是做什么的呢?好吧,它知道如何连接字符串,因此它将 [] 和 5 都转换为字符串,结果是字符串值“5”。
What's the deal with the comparison operators ==
and ===
? Why are there two comparison operators?
与比较运算符==
和 有===
什么关系?为什么有两个比较运算符?
==
is not immune to JavaScript's type conversion behavior. Expressions such as 5 == “5”
will evaluate to true because JavaScript will attempt to convert one of them so that it's comparing the same type of data.
==
不能免于 JavaScript 的类型转换行为。诸如此类的表达式5 == “5”
将评估为真,因为 JavaScript 将尝试转换其中之一,以便比较相同类型的数据。
In many cases, that's not desirable because you probably want to know if some data you're comparing against is of a different type so that you can decide what to do about it. That's where the ===
operator comes in. When you use ===
, no type conversion will take place. Therefore, the expression 5 === “5”
will evaluate to false.
在许多情况下,这是不可取的,因为您可能想知道要比较的某些数据是否属于不同类型,以便您可以决定如何处理。这就是===
运算符的用武之地。当您使用 时===
,不会发生类型转换。因此,表达式的5 === “5”
计算结果为 false。
回答by Claudiu
In Python if you try to add, say, strings and integers, you get an error:
在 Python 中,如果您尝试添加字符串和整数,则会出现错误:
>>> "hi" + 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
Yet in JavaScript, you don't. The 10
gets converted to a string:
然而在 JavaScript 中,你没有。将10
被转换为字符串:
> "hi" + 10
"hi10"
"Type coercion" is just a fancy misnomer for the above. In actuality, neither language has "types" in the sense of Java or C or other languages with static type systems. How the languages treat interactions between the various non-statically-typed values is a matter of choice and convention.
“类型强制”只是上面的一个花哨的用词不当。实际上,这两种语言都没有 Java 或 C 或其他具有静态类型系统的语言意义上的“类型”。语言如何处理各种非静态类型值之间的交互是一个选择和约定的问题。
回答by PRagh
let me explain type coercion with the following example
让我用下面的例子解释类型强制
Type Coercion means Javascript automatically (on-the-fly) converts a variable from one datatype to another
类型强制意味着 Javascript 自动(即时)将变量从一种数据类型转换为另一种数据类型
Ex: 123 + "4"
generally raises an error but in Javascript due to type coercion, it results in 1234
a string
例如:123 + "4"
通常会引发错误,但在 Javascript 中由于类型强制,它会产生1234
一个字符串
if(23 == "23"){
console.log(" this line is inside the loop and is executed ");
}
In the above code, because of type coercion - JavaScript thinks 23
(number) and "23"
(string) are the same thing. this makes the condition true and prints the console.log
在上面的代码中,由于类型强制 - JavaScript 认为23
(number) 和"23"
(string) 是一回事。这使条件为真并打印 console.log
In the other case
在另一种情况下
if(23 === "23"){
console.log(" this line is inside the loop and is NOT executed");
}
In ===
case Javascript doesn't do Type Coercion, and since 23
is a number and "23"
is String and because of ===
these two datatypes are different and that leads to the false in condition. It does not print the console.log
在===
情况下,JavaScript没有做类型强制,并且因为23
是一个数字,"23"
是String,并因为===
这两种数据类型是不同的,导致病情的假。它不打印 console.log
In simple words
简单来说
In this case =
it is an assignment operator - which assigns values such as var a = 3;
, etc
在这种情况下,=
它是一个赋值运算符 - 它分配诸如var a = 3;
等的值
(below operators are for comparison)
(以下运算符用于比较)
In this case ==
Javascript converts/coerces the datatype to another and then compares it.
在这种情况下,==
Javascript 将数据类型转换/强制转换为另一种数据类型,然后进行比较。
In this case ===
Javascript doesn't convert/coerces the datatype
在这种情况下,===
Javascript 不会转换/强制数据类型
In order to avoid bugs and for debugging purposes ===
is mostly used
为了避免错误和调试目的===
,主要使用
Please let me know the accuracy of the above information.
请让我知道上述信息的准确性。
回答by Willem van der Veen
What is coercion:
什么是强制:
Type coercion in javascript occurs when the Javascript engine has to perform a certain operation for which it needs data to be in a certain type. When the engine encounters data in a certain type that is not applicable for the operation it then coerces the data into a certain type. This is needed because variables in javascript are dynamically typed, which means that a given variable can be assigned a value of any type.
当 Javascript 引擎必须执行需要数据为特定类型的特定操作时,就会发生 javascript 中的类型强制。当引擎遇到某种类型的数据不适用于该操作时,它就会将数据强制转换为某种类型。这是必需的,因为 javascript 中的变量是动态类型的,这意味着可以为给定的变量分配任何类型的值。
Example:
例子:
if(1){
// 1 gets coerced to true
}
if(4 > '3') {
// 3 gets coerced into a number
}
44 == "44" // true, the string 44 gets converted to a nr
Boolean coercion:
布尔强制:
In javascript coercion, all values are converted to true
except for the following values which are coerced to false
:
在 javascript coercion 中,true
除了以下被强制转换为 的值外,所有值都被转换为false
:
console.log(!!""); // false
console.log(!!0); // false
console.log(!!null); // false
console.log(!!undefined); // false
console.log(!!NaN); // false
console.log(!!false); // false
Also notice that in the above example that the double ! operator is used. The ! mark operator coerces a value into a boolean with the opposite value. We can use this operator twice to convert any value into a boolean.
还要注意,在上面的例子中,double ! 使用运算符。这 !标记运算符将一个值强制转换为具有相反值的布尔值。我们可以两次使用此运算符将任何值转换为布尔值。
回答by Crayon Violent
a == b
means javascript will evaluate a
against b
based on if the values can be evaluated equally. For example, false == 0
will evaluate true because 0 is also the value of Boolean false. However, false === 0
will evaluate false because strictly comparing, 0 is not the same physical value as false. Another example is false == ''
So basically loose comparison vs. strict comparison, because javascript is a loosely typed language. That is to say, javascript will attempt to convert the variable based on the context of the code, and this has the effect of making things equal if they are not strictly compared. php also has this behavior.
a == b
这就意味着JavaScript将评估a
对b
基于其中的值是否可以同样评价。例如,false == 0
将评估为真,因为 0 也是布尔假的值。但是,false === 0
将评估为 false 因为严格比较,0 与 false 不是相同的物理值。另一个例子是false == ''
基本上松散比较与严格比较,因为 javascript 是一种松散类型的语言。也就是说,javascript 将尝试根据代码的上下文来转换变量,如果不严格比较它们,这会产生相等的效果。php 也有这种行为。
回答by Mahdi Salehian
Type coercion is the process of converting value from one type to another (such as string to number, object to boolean, and so on). Any type, be it primitive or an object, is a valid subject for type coercion. To recall, primitives are: number, string, boolean, null, undefined + Symbol (added in ES6).
类型强制是将值从一种类型转换为另一种类型(例如字符串到数字、对象到布尔值等)的过程。任何类型,无论是原始类型还是对象,都是类型强制的有效主体。回想一下,原语是:数字、字符串、布尔值、空值、未定义 + 符号(在 ES6 中添加)。
Type coercion can be explicit and implicit.
类型强制可以是显式和隐式的。
When a developer expresses the intention to convert between types by writing the appropriate code, like Number(value), it's called explicit type coercion (or type casting).
当开发人员通过编写适当的代码(如 Number(value))来表达在类型之间进行转换的意图时,这称为显式类型强制(或类型转换)。
Since JavaScript is a weakly-typed language, values can also be converted between different types automatically, and it is called implicit type coercion. It usually happens when you apply operators to values of different types, like 1 == null, 2/'5', null + new Date(), or it can be triggered by the surrounding context, like with if (value) {…}, where value is coerced to boolean.
由于 JavaScript 是弱类型语言,值也可以在不同类型之间自动转换,称为隐式类型强制。当您将运算符应用于不同类型的值时,通常会发生这种情况,例如 1 == null、2/'5'、null + new Date(),或者它可以由周围的上下文触发,例如 if (value) {... },其中值被强制为布尔值。
here is some example for implicit type coercion:
这是隐式类型强制的一些示例:
true + false
12 / "6"
"number" + 15 + 3
15 + 3 + "number"
[1] > null
"foo" + + "bar"
'true' == true
false == 'false'
null == ''
!!"false" == !!"true"
[‘x'] == ‘x'
[] + null + 1
[1,2,3] == [1,2,3]
{}+[]+{}+[1]
!+[]+[]+![]
new Date(0) - 0
new Date(0) + 0
read more: https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/
阅读更多:https: //www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/
回答by Mister P
var str = 'dude';
console.log(typeof str); // "string"
console.log(!str); // false
console.log(typeof !str); // "boolean"
Example of a variable which is initially declared as a string being coerced into boolean value with the ! operator
最初声明为字符串的变量示例被强制转换为布尔值!操作员
回答by A.S.Abir
If data type is not equal with each other then Coercion Happen. like 3 == "3" or boolen == integer
如果数据类型彼此不相等,则会发生强制转换。像 3 == "3" 或 boolen == 整数