在JavaScript中,我尝试执行以下语句
var x = 1+"2"-3; //Anser is 9.
var y = 1-"2"+4 //Anser is 3.对于这样的操作,什么被转换为什么?
我猜是1+"2" = 12(number)然后是12-3
发布于 2014-06-22 01:43:21
-将这两个操作数转换为数字。但是如果其中一个操作数到+是一个字符串,另一个操作数就会被转换成字符串,并且它是一个串联。比如"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这就是过程。
发布于 2014-06-22 01:43:50
方案I
步骤1:
1 + "2" => "12" //concatenation happened第二步
"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 happenshttps://stackoverflow.com/questions/24344192
复制相似问题