为什么字符串数字加法不能直观地合并

为什么最后一个操作返回 20?

console.log(2 + 2); // equals 4
console.log("2" + "2"); // equals "22"
console.log(2 + 2 - 2); // equals 2
console.log("2" + "2" - "2"); // equals 20

回答

+-从左到右评估。当任一操作数为字符串时,结果为串联。当两者都是数字时,结果是加法。

相比之下,-总是将双方强制为数字。

'2' + '2' - '2'

// left-to-right
('2' + '2') - '2'
// both sides are strings, so concatenate
'22' - '2'
// operator is -, so coerce both sides to numbers
22 - 2
20


以上是为什么字符串数字加法不能直观地合并的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>