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

Siy*_*iya 2 javascript

为什么最后一个操作返回 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
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 11

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

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

'2' + '2' - '2'
Run Code Online (Sandbox Code Playgroud)

// 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
Run Code Online (Sandbox Code Playgroud)