将数组转换为嵌套对象列表-Eloquent Javascript 4.3 [英] Convert an array to a list of nested objects - Eloquent Javascript 4.3
问题描述
我正在从Eloquent Javascript,第4章- A列表相当长的一段时间,我试图了解此特定功能的工作原理:
I am looking at this exercise from the book Eloquent Javascript, Chapter 4 - A List for quite some time and I'm trying to understand how this particular function works:
function arrayToList(array) {
let list = null;
for (let i = array.length - 1; i >= 0; i--) {
list = {value: array[i], rest: list};
}
return list;
}
console.log( arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
即使在调试器的监视"窗口中添加了list
之后,我仍然看不清以下内容:
Even after adding the list
to the Watch window in the Debugger I can't clearly see the following:
1.在每次迭代期间,如何精确地将list = {value: array[i], rest: list};
中的语句附加到嵌套对象的rest
属性中?
1. How does exactly the statement from list = {value: array[i], rest: list};
get appended to the rest
property of the nested object, during each iteration?
显然,没有使用点.rest
或方括号['rest']
表示法,也没有明确指定在以后的每次迭代过程中,我们都引用该对象或其以后嵌套的对象的属性,那么它是如何得到的附加到每个下一个嵌套对象的属性.
Obviously, the dot .rest
or bracket ['rest']
notation are not being used, and it is not being explicitly specified that during every following iteration we are referring to the property of the object or its later nested objects, so how does it get appended to the property of each next nested object.
我希望每次迭代都覆盖list
对象的内容,但事实并非如此.
I am expecting for every iteration to overwrite the contents of the list
object, but this is not the case.
推荐答案
TL; DR:在每次迭代中,我们都会创建一个新对象,其中包含上一次迭代中的对象.
在list = {value: array[i], rest: list};
行中,首先评估=
右侧的语句.这意味着我们创建一个对象{value: array[i], rest: list}
,其中包含array[i]
和list
的当前值.在第一次迭代中,list
是null
并且array[i]
是20,因此对象看起来像这样:
In the line list = {value: array[i], rest: list};
, the statement on the right of the =
gets evaluated first. This means we create an object {value: array[i], rest: list}
, containing the current values of array[i]
and list
. In the first iteration, list
is null
and array[i]
is 20, so the object looks like this:
{value: 20, rest: null}
然后我们才将此对象分配给list
.
Only then do we assign this object to list
.
在下一次迭代中,list
不再是null
,而是{value: 20, rest: null}
.因此,现在,我们创建并分配给list
的对象如下所示:
In the next iteration, list
isn’t null
anymore, but {value: 20, rest: null}
. So now, the object we create and assign to list
looks like this:
{value: 10, rest: {value: 20, rest: null}}
这篇关于将数组转换为嵌套对象列表-Eloquent Javascript 4.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!