将数组转换为嵌套对象列表 - Eloquent Javascript 4.3

问题描述 投票:0回答:2

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

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

1.在每次迭代期间,list = {value: array[i], rest: list};中的语句到底是如何附加到嵌套对象的rest属性的?

显然,没有使用点.rest或括号['rest']表示法,并且没有明确指出在每次后续迭代中我们指的是对象的属性或其后来的嵌套对象,那么它如何被附加到属性每个下一个嵌套对象。

我期望每次迭代都会覆盖list对象的内容,但事实并非如此。

javascript arrays list object nested
2个回答
1
投票

TL; DR:在每次迭代中,我们创建一个包含上次迭代对象的新对象。

list = {value: array[i], rest: list};行中,首先评估=右侧的声明。这意味着我们创建了一个对象{value: array[i], rest: list},其中包含array[i]list的当前值。在第一次迭代中,listnullarray[i]是20,所以对象看起来像这样:

{value: 20, rest: null}

只有这样我们才能将这个对象分配给list

在下一次迭代中,list不再是null,而是{value: 20, rest: null}。所以现在,我们创建并分配给list的对象如下所示:

{value: 10, rest: {value: 20, rest: null}}

1
投票

我试着在这里解释一下。如果有什么不清楚,请告诉我

function arrayToList(array) {
  // declare a empty variable to use is as a list
  let list = null;

  // Now iterate from the last element to the first. Example [10, 20]
  for (let i = array.length - 1; i >= 0; i--) {

    // iteration 1: i = 1 
    // we assign to list...
    list = {
        //the value of the current element
        value: array[i], // value = 20
        // the current list value before current assign
        rest: list // rest = null
    };
    // now it is assigned. list = {value: 20, rest: null}

    // ....

    // iteration 2: i = 0
    // we assign to list...
    list = {
        //the value of the current element
        value: array[i], // value = 10
        // the current list value before current assign
        rest: list // rest = {value: 20, rest: null}
    };
    // now it is assigned. list = {value: 10, rest: {value: 20, rest: null}}

  }
  return list;
}
© www.soinside.com 2019 - 2024. All rights reserved.