令人惊讶的简单操作结果

时间:2014-06-21 17:40:47

标签: javascript jquery

在JavaScript中,我尝试执行以下语句

var x = 1+"2"-3; //Anser is 9.
var y = 1-"2"+4 //Anser is 3.

对于这样的操作,什么转换为什么?

我猜1+"2" = 12(number)然后是12-3

2 个答案:

答案 0 :(得分:3)

-将两个操作数转换为数字。但是,如果+的任一操作数是字符串,则另一个操作数转换为字符串,它是串联的。像"Hi, " + "how are you?" = "Hi, how are you?"那样你的答案是正确的。

var x = 1+"2"-3; 
// concats the string as 12 and then subtracts...
12 - 3 = 9
var y = 1-"2"+4 
// converts to numbers and subtracts, making -1 and then adds 4 giving out 3
-1 + 4 = 3

这是一个过程。

答案 1 :(得分:2)

情景I

第1步:

1 + "2" => "12" //concatenation happened

第2步

"12" - 3 => 9 //String widens to number since we are using - symbol here.

情景II

第1步:

1 - "2" => -1 //String widens to number since we are using - symbol here.

第2步:

-1 + 4 => 3 //Normal addition happens