JavaScript隐式强制 [英] JavaScript Implicit Coercion

查看:72
本文介绍了JavaScript隐式强制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于隐式和显式强制的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆