雄辩的JavaScript:第4章
我需要帮助逐步了解此解决方案是如何实现链接列表的雄辩的JavaScript:第4章,javascript,arrays,Javascript,Arrays,我需要帮助逐步了解此解决方案是如何实现链接列表的 function arrayToList(array) { let result = {}; if (Array.isArray(array)) { let currListItem = result; for (let item of array) { let newListItem = { value: item, rest: null }; if (
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;
}
另见:
array.isArray(array)
如果是,则为currListItem
分配一个空对象
现在迭代数组的每个项,并为每个项创建一个具有2个属性的新对象,值存储该项,其余项初始化为null
然后在这一行如果(typeof currListItem.rest==='undefined')
,检查currListItem对象中是否有rest属性。这样做是为了检查这是否是链接列表中的第一个节点
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;
}
如果If条件为true,则将节点newListItem分配给结果。然后将newListItem
分配给currlist
,并继续进行进一步的迭代
如果在第一次迭代后if条件变为false,我们需要将新对象与现有节点链接。因此,使用此行currListItem.rest=newListItem代码>,我们正在将新对象链接到上一个节点的rest字段
最后,我们将这个新节点标记为currListItem
,以便下一次迭代
属性名称应该是下一个,而不是rest,因为它将使理解更容易。“最后,我们将此新节点标记为currListItem,以便下一次迭代。”
这是怎么回事?似乎要继续构建链接列表,您不应该将其设置为新节点?请发布函数的实际文本,而不是屏幕截图。这个问题与git
有什么关系?我删除了git
标签。。。