[英]Confusing comma operator in JavaScript. Why does it work in such manner?
Could anybody explain why the output of the code 任何人都可以解释为什么代码输出
var a = [1,2];
console.log("Array item: " + a[a=a.toString(), 1]);
console.log("String char: " + a[1]);
looks like this? 看起来像这样吗?
Array item: 2
String char: ,
The question is why array didn't convert to string in the first console.log. 问题是为什么数组在第一个console.log中没有转换为字符串。 How do memory and pointers work in this case?
在这种情况下,内存和指针如何工作?
a[a = a.toString(), 1]
evaluates a
at first, which points to an array yet, then it replaces a
with a stringified a
which won't affect the already evaluated part, then accesses index 1
of the array. a[a = a.toString(), 1]
首先评估a
,它指向一个数组,然后将其替换a
不会影响已评估部分的字符串化a
,然后访问该数组的索引1
。 Its the same as: 它与:
var b = a;
a.toString();
b[1]
Now a[1]
evaluates to ,
because a
points to the string now, and therefore it gets the second character. 现在
a[1]
的计算结果为,
因为a
指向字符串现在,因此它得到了第二个字符。
Here is how the parser sees it: 解析器如何看待它:
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
What you're facing is evaluation order, access order and how the memory is storing the values. 您面临的是评估顺序,访问顺序以及内存如何存储值。
Javascript as other languages evaluates from right to left, Although the comma operator evaluates first a=a.toString()
in memory a
equals to [1,2]
because the most at right value will be evaluated first before modifying the variable a
, so a[1] = 2
. 与其他语言一样,Javascript从右到左进行评估,尽管逗号运算符首先评估内存中
a
a=a.toString()
等于[1,2]
因为在修改变量a
之前,首先评估最右边的值,因此a[1] = 2
。
After that access, the variable a
equals to "1,2"
and a[1] = ,
, in memory a String is like an array of chars and is possible to access using indexes. 访问之后,变量
a
等于"1,2"
且a[1] = ,
,在内存中,String就像一个char数组,可以使用索引进行访问。
This is how the access occurs: 这是访问发生的方式:
+------------+-------------+
| 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.