JavaScript隐式强制 [英] JavaScript Implicit Coercion
问题描述
我正在阅读关于隐式和显式强制的JavaScript教程。
I'm reading a JavaScript tutorial on implicit and explicit coercion.
隐式强制背后会发生什么?
What happens in the background with respect to implicit coercion?
var a = "42";
var b = a * 1; //this is implicitly coerced to 42 -- the number
隐式强制 总是 强迫一个号码?如果我们想要根据以下Python示例执行某些操作,该怎么办?
Does implicit coercion ALWAYS coerce to a number? What if we wanted to do something a per the below Python example.
我很困惑,因为其他语言如Python会给你一个结果如下。
I'm getting confused because other languages such as Python would give you a result as per below.
a = "3";
b = 9;
print a * b; //This would print 333333333 -- the string
推荐答案
我为了方便起见,我会留下这个隐含强制的结论:
I will leave this here for your convenience to draw some conclusions as far as implicit coercion goes:
true + false // 1
12 / "6" // 2
"number" + 15 + 3 // 'number153'
15 + 3 + "number" // '18number'
[1] > null // true
"foo" + + "bar" // 'fooNaN'
'true' == true // false
false == 'false' // false
null == '' // false
!!"false" == !!"true" // true
['x'] == 'x' // true
[] + null + 1 // 'null1'
[1,2,3] == [1,2,3] // false
{}+[]+{}+[1] // '0[object Object]1'
!+[]+[]+![] // 'truefalse'
new Date(0) - 0 // 0
new Date(0) + 0 // 'Thu Jan 01 1970 02:00:00(EET)0'
但长话短说,规则是这样的,除非你做一个明确的强制,Javascript会根据操作和操作数类型为你做一个(因此隐含) 参与其中。
But long story short the rules are such that unless you do an explicit coercion Javascript would do one for you (hence implicit) based on the operation and the operand types involved.
您可以查看 JavaScript强制规则表以获得完整的预期。
You can check the JavaScript Coercion Rules table to get a full prospective.
note :
JavaScript强制总是得到一个
的标量原始值,如字符串,数字,
或布尔值。没有强制导致像
对象或函数这样的复杂值。
JavaScript coercions always result in one of the scalar primitive values, like string, number, or boolean. There is no coercion that results in a complex value like object or function.
这篇关于JavaScript隐式强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!