冗长的JavaScript:第4章



我需要帮助逐步了解这个解决方案是如何实现链表的。

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;
}

另请参阅:

  • https://eloquentjavascript.net/04_data.html
  • https://gist.github.com/jonurry/9ceb8e580072fdd4d9d58bb2a9edc5da

首先检查给定的参数数组是否实际上是一个数组Array.isArray(array)

如果是,则为currListItem指定一个空对象。

现在迭代数组的每个项,并为每个项创建一个具有2个属性的新对象,value存储该项,rest初始化为null。

然后在这行if (typeof currListItem.rest === 'undefined')中,检查currListItem对象中是否有rest属性。这样做是为了检查这是否是链表中的第一个节点。

如果If条件为true,则将节点newListItem分配给result。然后将newListItem分配给currlist,并继续进行进一步的迭代。

如果if条件在第一次迭代后变为false,我们需要将新对象与现有节点链接起来。因此,使用这行currListItem.rest = newListItem;,我们将新对象与上一个节点的rest字段链接起来。

最后,我们将这个新节点标记为currListItem,用于下一次迭代。

下一个应该是属性名称,而不是rest,因为这将使理解更容易。

"最后,我们将这个新节点标记为currListItem,用于下一次迭代">

这是怎么回事?似乎要继续构建链表,不应该将其设置为新节点?

最新更新