【发布时间】:2017-05-19 04:35:07
【问题描述】:
我正在尝试在 LinkedList 构造函数上创建一个方法,该构造函数可以接收一个函数并在每个节点项上调用它。这是我目前所拥有的:
这是我的构造函数:
function LinkedList() {
this.head = this.tail = null;
}
我有一个我测试过的 addToTail 方法:
LinkedList.prototype.addToTail = function (item) {
let newNode = new ListNode(item);
if (this.tail) {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
} else {
this.head = newNode;
this.tail = this.head;
}
return this;
};
地点:
function ListNode(item, prev, next) {
this.item = item;
this.next = next || null;
this.prev = prev || null;
}
现在我正在尝试在每个节点项上调用一个函数:
LinkedList.prototype.forEach = function (iterator) {
return this.map(iterator (item))
谁能向我解释为什么我的 forEach 返回一个 []?我也尝试了console.log(this)并且也得到了[]。解决这个问题的最佳方法是什么?谢谢!
【问题讨论】:
-
向我们展示您如何定义
LinkedList.prototype.map。由于您(错误地)在那里转发,所以它返回数组的原因应该很明显。 -
'item' in iterator(item) 将是未定义的。
-
我试图使用 Array.prototype.map() 方法。但我只记得我的链表不是数组,所以我现在完全迷路了
标签: javascript data-structures linked-list