问题描述:

I'm going through Data Structures and Algos by O'Reily and I'm on page 54 where I've already written out my list function and I'm testing out my append and remove functions. My remove function won't actually work and I used what is in the book. Here is the function:

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;

}

When I try to run

names.remove("Raymond");

like in the book, "Raymond" is not removed from the list. Not sure what I could be wrong. Here is my code:

 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());

网友答案:

Nothing's being removed because your find method's loop is wrong.

Change:

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

To:

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

Fixed: https://jsfiddle.net/vjd7zocd/

相关阅读:
Top