繁体   English   中英

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=a.toString()等于[1,2]因为在修改变量a之前,首先评估最右边的值,因此a[1] = 2

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

这是访问发生的方式:

          +------------+-------------+
          | 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.
          +--------+-----------------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM