简体   繁体   中英

How do I iterate through an instance of this List class in JavaScript

I am trying to iterate over a list var names = new List(); the following way:

var names = new List();
names.append('tom');
names.append('bob');
names.append('marshal');
names.append('Cartman');
names.append('Randy');

for(names.top(); names.currentPosition() < names.length(); names.next()) {
  console.log(names.getElement()); // going on and on stuck at one index! infinite loop!!!
}

I am getting an infinite loop with an unchanging index of the list. What might be going wrong?

Assume the list has already been filled with values using an append method. It is definitely not empty. Here is the implementation of the List class:

function List() {
  this.dataStore = [];
  this.listSize = 0;
  this.position = 0;
}

List.prototype = {

  clear: function() {
    delete this.dataStore;
    this.dataStore = [];
    this.position = this.listSize = 0;
  },

  toString: function() {
    return this.dataStore.join(' \n');
  },

  getElement: function() {
    return this.dataStore[this.position];
  },

  append: function(el) {
    this.dataStore[this.listSize++] = el;
  },

  top: function() {
    this.position = 0;
  },

  bottom: function() {
    this.position = this.listSize - 1;
  },

  prev: function() {
    if(this.position > 0) {
      this.position--;
    }
  },

  next: function() {
    if(this.position < this.listSize - 1) {
      this.position++;
    }
  },

  length: function() {
    return this.listSize;
  },

  currentPosition: function() {
    return this.position;
  },

};

Your next() function won't increment the this.position value past this.listSize - 1 and therefore your conditional portion of the for loop will always evaluate to true since your currentPosition() will always be less than your length() .

Take for example, your List having 1 element in it. Here's the for loop values:

names.top() = 0
names.currentPosition() = 0
names.length() = 1

Calling names.next() checks this.position < this.listSize - 1 . This can be rewritten: 0 < (1 - 1) . So next doesn't increment this.position and your for loop runs infinitely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM