gpt4 book ai didi

javascript - 在循环中分配给变量之前评估右侧表达式

转载 作者:行者123 更新时间:2023-12-03 01:49:10 24 4
gpt4 key购买 nike

我无法理解此问题的答案:Making a list out of an Array

对于以下函数(从数组创建列表)

function arrayToList(array) 
{
var list = null;
for (var i = array.length-1; i>=0; i--) {
list = {value: array[i], rest: list};
}
return list;
}

我的问题是:为什么现有列表没有被新列表覆盖,而是新列表被替换到其余属性中?

在所选答案的评论中,解释说:

Because the whole right hand side expression of the assignment is evaluated/executed before it is actually assigned to the left hand side variable. So while the new object is being constructed, the old one is untouched and so it's value can be used during that construction. just like var a = 1; a = 1 + a; a will be 2 after this, its value doesn't change until after the right hand side is evaluated. The list is the same, we're not editing list, we're changing what it is a reference to. I.e. it was a reference to {value: 3, rest: null} now it's a reference to a new object {value: 2, rest: {value: 3, rest:
null}}
.

我无法理解这个答案,“在构造新对象时,旧对象未受影响,因此在此期间可以使用它的值”是什么意思。

这个循环的行为如何像递归而不是不断重写列表?

最佳答案

why is the existing list not being overwritten by the new list and instead the new list is replaced into the rest property?

list = {value: array[i], rest: list};
//---------------------------^^^^^^

list对象被覆盖,但是,由于上述原因,在重新分配之前,之前的值存储在rest中。

"while the new object is being constructed, the old one is untouched and so it's value can be used during that".

为了便于理解,上面的行可以解释如下

var temp = {value: array[i], rest: list};
list = temp;

正如您所看到的,首先 list 的先前值存储在对象的 rest 中,然后 list 被重新分配该对象。

关于javascript - 在循环中分配给变量之前评估右侧表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50493724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com