【发布时间】:2015-10-11 18:32:22
【问题描述】:
我正在努力了解这种单链表实现在 JavaScript 中的工作原理。具体来说,就是 add() 方法中第 23 行和第 35 行的 return 语句。
-- 在第 23 行,为什么我们要返回节点,而不是使用 'return';反而? -- 在第 35 行,为什么我们要返回 node,因为它似乎不会影响代码的功能?
谢谢!
// Constructors (Node and SinglyList)
function Node(data) {
this.data = data;
this.next = null;
}
function SinglyList() {
this._length = 0;
this.head = null;
}
//Add Method
SinglyList.prototype.add = function(value) {
var node = new Node(value),
currentNode = this.head;
if(!currentNode) {
this.head = node;
this._length++;
// return the new Node object. (why can't we just use return; here?)
return node;
}
//USE CASE 2: NON-EMPTY LIST
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
this._length++;
// return statement doesn't seem to do anything here.
return node;
};
var list = new SinglyList();
list.add(1);
list.add(2);
list.add('foo');
console.log(list.head);
【问题讨论】:
-
'为什么需要' - 它不需要需要,但如果您或其他人以后想要该功能,它就在那里。
-
好点。更改了问题的措辞。