[英]Doubly linked list can call a function on each node item?
我正在嘗試在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);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.