为什么字符串在 post 递增(something++)和加 1(something = something +1)时产生不同的输出?

Why do strings produce a different output for post increment (something++) vs. adding 1 (something = something +1)?

我们知道编程语言中的post-增量和预增量。据我所知,post-increment 表示为下一条语句增加值。所以,something++ 等同于 something = something + 1,不是吗?

但是为什么 something = something + 1something++something 是字符串时产生不同的输出?

let something = "5";
let anything = 5;

something = something + 1;
console.log(something); // "51"

anything = anything + 1;
console.log(anything); // 6
let something = "5";
let anything = 5;

something++;
console.log(something); // 6

anything++;
console.log(anything); // 6

我知道自动类型转换,但为什么 something + 1 被强制转换为字符串,而 something++ 被转换为数字?

这是两个不同的运算符

++ 是 post 递增它隐式地尝试将操作数强制转换为数字然后执行递增 ++ Ref

let increment = (val) =>{
  return val++
}

console.log(increment('5'))
console.log(increment(''))
console.log(increment([]))
console.log(increment({}))
console.log(increment(undefined))

而另一个用于数值时是加法,但用作字符串的连接 + Ref

let increment = (val) => {
  return val + 1
}

console.log(increment('5'))
console.log(increment(''))
console.log(increment([]))
console.log(increment({}))
console.log(increment(undefined))

如果你阅读 specification for the ++ operator,你会发现第 2 步强制其操作数为数字,而 + 则不然。

12.4.4 Postfix Increment Operator

12.4.4.1 Runtime Semantics: Evaluation

UpdateExpression : LeftHandSideExpression ++

  1. Let lhs be the result of evaluating LeftHandSideExpression.
  2. Let oldValue be ? ToNumber(? GetValue(lhs)).
  3. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 12.8.5).
  4. Perform ? PutValue(lhs, newValue).
  5. Return oldValue.