在javascript中为列表创建了一个删除函数,但它没有删除元素

时间:2017-01-04 01:06:19

标签: javascript

我正在浏览O'Reily的Data Structures和Algos,我在第54页,我已经写出了我的列表函数,我正在测试我的追加和删除函数。我的删除功能实际上不起作用,我使用了本书中的内容。这是功能:

function remove(element)
{
    var foundAt = this.find(element);
    if (foundAt > -1)
    {
        // splice(index, howmany, item1, ...., itemX)
        this.dataStore.splice(foundAt, 1);
        --this.listSize;
        return true;
    }
    return false;
}

当我尝试运行时

names.remove("Raymond");
像书中一样,“雷蒙德”没有从列表中删除。不知道我错了什么。这是我的代码:

    function List() {
      this.listSize = 0;
      this.pos = 0;
      this.dataStore = []; //initializes an empty array to store list     elements
      //this.clear = clear;
      this.find = find;
      this.toString = toString;
      //this.insert = insert;
      this.append = append;
      this.remove = remove;
      //this.front = front;
      //this.end = end;
      //this.prev = prev;
      //this.next = next;
      this.length = length;
      //this.currPost = currPos;
      //this.moveTo = moveTo;
      //this.getElement = getElement;
      this.length = length;
      //this.contains = contains;
    }

     // append an element
    function append(element) {
      this.dataStore[this.listSize++] = element;
    }

     // remove an element
    function find(element) {
      for (var i = 0; i < this.dataStore; ++i) {
        if (this.dataStore[i] == element) {
          return i;
        }
      }
      return -1;
    }

     // after the array is modified
     // listSize is decremented by 1 to reflect the size of the list
    function remove(element) {
      var foundAt = this.find(element);
      if (foundAt > -1) {
        // splice(index, howmany, item1, ...., itemX)
        this.dataStore.splice(foundAt, 1);
        --this.listSize;
        return true;
      }
      return false;
    }

    function length() {
      return this.listSize;
    }

    function toString() {
      return this.dataStore;
    }

    var names = new List();
    names.append("Cynthia");
    names.append("Raymond");
    names.append("Barbara");
    console.log(names.toString());
    names.remove("Raymond");
    console.log(names.toString());

1 个答案:

答案 0 :(得分:3)

因为find方法的循环错误而无法删除任何内容。

更改

for (var i = 0; i < this.dataStore; ++i)

for (var i = 0; i < this.dataStore.length; ++i)

<强>固定https://jsfiddle.net/vjd7zocd/