JavaScript Implicit Coercion

社会主义新天地 提交于 2020-01-02 05:15:13

问题


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

Does implicit coercion ALWAYS coerce to a number? What if we wanted to do something a per the below Python example.

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

回答1:


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'

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.

You can check the JavaScript Coercion Rules table to get a full prospective.

One thing to note:

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.



来源:https://stackoverflow.com/questions/52639014/javascript-implicit-coercion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!