三元运算符未按预期处理 post 增量

Ternary operator doesn't handle post-increments as expected

所以这可能是一个愚蠢的问题,但我时不时地 运行 陷入这个语法错误并且似乎无法吸取教训 - 因为我根本不明白为什么会这样不起作用。

出于某种原因,三元运算符无法处理递增或递减。

在控制台中,我发现了这些结果:

  // Firstly
var iteration = undefined; 

  // Expected increment, unexpected result
iteration = iteration == undefined ? 0 : iteration++;  //returns 0 every time

  // Then I thought maybe ternary doesn't return assignments
iteration = iteration == undefined ? 0 : iteration+=1; //increments iteration

  // Works as expected
iteration = iteration == undefined ? 0 : iteration+1;  //increments iteration

在搜索答案时,我发现另一个用户有

经过更多搜索,我发现预增量工作正常:

iteration = iteration == undefined ? 0 : ++iteration; //increments iteration

came across this answer 试图确定为什么预增量有效。

对我来说它为什么有效而 post-increment 没有 - 有点。我想如果三元操作顺序那样工作,在某些时候增量值可能会被初始值覆盖,但这就是我能想到的。

但实际上,我从 post 增量中获得的预期行为是返回迭代,然后迭代它...after.

比如这段代码:

var bar = undefined;
//foo is set immediately and bar is incremented after it is returned
foo = bar == undefined ? bar=0 : bar++; //sets foo to be what bar was before the increment

希望你能在这里忍受我。我确实明白,在找到许多可靠和直接的方法来完成工作后,我不需要答案,但我很困惑为什么它会这样工作。

问题:

为什么三元运算符不更新返回的 post-增量(或 post固定)值 - 在返回后?

A 表示

counter++ evaluates to the current value of counter, then increments it. You would be assigning the old value of counter back to counter after you've incremented.

但我仍然不明白为什么操作顺序会这样。

Another helpful Pre-increment vs Post-increment 用于 C++(具有讽刺意味的搞笑答案)

无论解释器是否遇到调用预增量或 post 增量的表达式,都会在解析表达式之前立即 重新分配变量。例如:

iteration = iteration == undefined ? 0 : iteration++;

就像

function doPostIncrement() {
  const preIncrementValue = increment;
  increment = increment + 1;
  return preIncrementValue;
}
iteration = iteration == undefined ? 0 : doPostIncrement();

此外,赋值解析为值,因此

iteration = iteration == undefined ? 0 : iteration+=1; //increments iteration

就像

function addOneToIncrementAndReturnIncrement() {
  increment = increment + 1;
  return increment;
}
iteration = iteration == undefined ? 0 : addOneToIncrementAndReturnIncrement();

实际上不是一个函数调用,但并没有什么不同,因为重新分配是在函数解析之前完成的,或者在 pre / post-递增表达式解析。

在赋值表达式中,首先计算整个右侧,然后将其结果值赋给左侧。这意味着 post 增量表达式需要先求值并转换为一个值,然后将其分配给左侧。 post 增量运算符不知道它是哪个更大的表达式的一部分。它将以原子方式进行评估。即不会先return它的值,然后完成赋值操作,然后然后完成post自增操作。当评估表达式 iteration++ 时,iteration 的值将递增 并且 表达式结果会立即生成 iteration 的原始值。