我正在尝试在 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) 也得到了 []。解决这个问题的最佳方法是什么?谢谢!
最佳答案
也许,这不是最好的解决方案,但是,您可以遍历链表并在每个成员上执行函数 func
:
LinkedList.prototype.forEach = function (func) {
let cur = this.head;
while (cur) {
func(cur); // Call your function
cur = cur.next;
}
};
或者,如果您想将 map
函数添加到链表中,
LinkedList.prototype.map = function (func) {
let res = [];
let cur = this.head;
while (cur) {
res.push(func(cur)); // Call your function and add the result
cur = cur.next;
}
return res;
};
然后,您可以调用:
LinkedList.prototype.forEach = function (func) {
this.map(function (e) { return e; }).forEach(func);
};
关于javascript - 双向链表可以在每个节点项上调用一个函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44061538/