将数组转换为嵌套对象列表 - Eloquent Javascript 4.3 [英] Convert an array to a list of nested objects - Eloquent Javascript 4.3

查看:51
本文介绍了将数组转换为嵌套对象列表 - Eloquent Javascript 4.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Eloquent Javascript 第 4 章 - A List 一书中的这个练习很长一段时间,我试图了解这个特定功能是如何工作的:

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 添加到 Watch 窗口后,我也无法清楚地看到以下内容:


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 的当前值>.在第一次迭代中,listnull 并且 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆