原型方法在某些情况下不是一个函数......为什么?

时间:2017-07-24 13:04:24

标签: javascript recursion linked-list prototype hoisting

链接列表相当新,所以我试图开发一种方法,从列表中删除一个节点。然后我会在函数recusivley(或循环)中运行该方法,直到删除某个值的所有节点。问题是当我尝试运行循环时出现错误,说原型方法不是函数被抛出。这是我的代码:

链接列表由以下内容制作:

  function ListNode(x) {
    this.value = x;
    this.next = null;
  }

方法:

ListNode.prototype.remove = function (val) {
  var origin = this;
  var current = this;

  //check head
  if (current.value === val) {
    if (current.next){
      origin = current.next
    }else{
      return [];
    }
  }else{
    //check between head and tail

    var previous = current;
    while(current.next){
      if (current.value === val){
        previous.next = current.next;
        return origin;
      }
      previous = current;
      current = current.next;
    }

    //check last
    if (current.value === val){
      previous.next = null;
    }
  }
  return origin;
}

用于删除值为k的所有节点:

function removeKFromList(l, k) {

  if (l) {
    var a = l.remove(k) //this alone doesn't throw the error
    while (a != l) {
      l = a;
      a = l.remove(k); //this with the while loop throws an error
      //if the line above were removed function would run without error
    }
  }
  return l;
}

我知道问题源于while循环中的行:

a = l.remove(k)

因为没有它,该功能运行良好。我可以更改while循环,以便函数以递归方式运行,如下所示:

...
if (l != a){
  l = removeKfromList(a, k)
}
...

然后仍然会抛出错误。

我的问题是为什么抛出错误?更具体地说,当a首先设置为l.remove(k)时,为什么不会抛出错误?为什么while循环/递归抛出错误? (抛出的错误特别是" l.remove()现在是一个函数")。

此外,如果有人有更好的方式做我正在尝试的事情,我总是想要学习新东西。

0 个答案:

没有答案