JavaScript 中令人困惑的逗号运算符。为什么它以这种方式工作?

Confusing comma operator in JavaScript. Why does it work in such manner?

任何人都可以解释为什么代码的输出

var a = [1,2];
console.log("Array item: " + a[a=a.toString(), 1]);
console.log("String char: " + a[1]);

看起来像这样?

Array item: 2                                                                   
String char: , 

问题是为什么数组在第一个 console.log 中没有转换为字符串。在这种情况下,内存和指针如何工作?

a[a = a.toString(), 1] 首先计算 a,它指向一个数组,然后用字符串化的 a 替换 a,这不会影响已经计算的部分,然后访问数组的索引 1。等于:

var b = a;
a.toString();
b[1]

现在 a[1] 计算为 , 因为 a 现在指向字符串,因此它得到第二个字符。

解析器是这样看的:

a[a = a.toString(), 1]
// Evaluation of a
[1, 2][a = a.toString(), 1]
// Evaluation of the comma operator, a is turned into a string
[1, 2][1]
// Prop access
2

您面临的是评估顺序、访问顺序以及内存如何存储值。

Javascript 因为其他语言从右到左求值,虽然逗号运算符在内存中首先求值 a=a.toString() a 等于 [1,2] 因为最右边的值在修改变量a之前会先求值,所以a[1] = 2.

访问之后,变量a等于"1,2"a[1] = ,,在内存中,字符串就像一个字符数组,可以使用索引访问。

访问是这样发生的:

          +------------+-------------+
          | Var a      | Access      |
          +------------+-------------+
       +--|    [1,2]   | a[1] -> 2   |-+---> This is the first access.
Memory |  +--------+-----------------+ |<--- Here the first value no longer exists and now a = String.
       +--|    "1,2"   | a[1] -> "," |-+---> This is the second access.
          +--------+-----------------+