操作数顺序更改时,Javascript类型转换具有奇怪的行为

我只是在编写一些JavaScript代码,并且在执行简单的算术运算时注意到一种非常奇怪的行为。

考虑以下代码:

let anyNumber = 10;
anyNumber = anyNumber + (12.512).toFixed(2); // toFixed() returns a String
console.log(anyNumber); // it will output 1012.512

// By changing the Order of the operands,there is no difference in operation and it basically concatenates both as a string.

let anotherNumber = 10;
anotherNumber = (12.512).toFixed(2) + anotherNumber;
console.log(anotherNumber);  // output 12.5110

该代码块将1012.512打印为字符串,因为可以理解操作数之一是String。但是我们对此情况做了一些修改,如下所述:

console.log((12.512).toFixed(2) + 10); // it will output 22.51

// Also if we change the order here,the output is very different.

console.log(10 + (12.512).toFixed(2)); // It will output 1012.51

问题是,如果我们更改表达式中操作数的顺序,它将检测到变化并表现出非常不同的行为,但是对于变量,即使变量{{1}的类型,它也不会有所区别}仍然是anyNumber

engkeluu 回答:操作数顺序更改时,Javascript类型转换具有奇怪的行为

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3150304.html

大家都在问