简体   繁体   中英

Eloquent JavaScript: Chapter 4

I need help understanding step by step what this solution is doing to achieve a linked list.

function arrayToList(array) {
  let result = {};
  if (Array.isArray(array)) {
    let currListItem = result;
    for (let item of array) {
      let newListItem = {
        value: item,
        rest: null
      };
      if (typeof currListItem.rest === 'undefined') {
        result = newListItem;
      } else {
        currListItem.rest = newListItem;
      }
      currListItem = newListItem;
    }
  }
  return result;
}

See also:

First check if the given argument array is actually an an array, Array.isArray(array)

If yes, then assign currListItem an empty object.

Now iterate over each item of the array and for each item create a new object with 2 properties, value which stores the item and rest which is initialized as null.

Then in this line if (typeof currListItem.rest === 'undefined') , check whether the currListItem object has a rest property in it. This is done to check whether this is is the first node in the linked list.

If the if condition is true, assign the node newListItem to result. Then assign newListItem to currlist and move on to further iterations.

Incase the if condition becomes false, which it will after the 1st iteration, we need to link the new object with the existing node. So, using this line currListItem.rest = newListItem; , we are linking the new object with the rest field of the previous node.

At the end we mark this new node as the currListItem , for next iteration.

Instead of rest the property name should have been next as it will make the understanding easier.

"At the end we mark this new node as the currListItem, for next iteration."

How does this work? It seems like to keep building the linked list you should not set it to the new node?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM