简体   繁体   English

如何在JavaScript中遍历此List类的实例

[英]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(); 我试图遍历一个列表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. 假定列表已经使用append方法填充了值。 It is definitely not empty. 绝对不是空的。 Here is the implementation of the List class: 这是List类的实现:

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() . 您的next()函数不会将this.positionthis.position this.listSize - 1 ,因此,由于currentPosition()始终小于length() ,因此for循环的条件部分将始终为true

Take for example, your List having 1 element in it. 例如,您的List中包含1个元素。 Here's the for loop values: 这是for循环值:

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

Calling names.next() checks this.position < this.listSize - 1 . 调用names.next()检查this.position < this.listSize - 1 This can be rewritten: 0 < (1 - 1) . 可以重写: 0 < (1 - 1) So next doesn't increment this.position and your for loop runs infinitely. 因此,接下来不增加this.position并且for循环无限运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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