gpt4 book ai didi

javascript - 列表迭代器进入无限循环 - Javascript

转载 作者:行者123 更新时间:2023-11-28 13:33:38 28 4
gpt4 key购买 nike

我使用 javascript 创建了一个列表,最后我有一个迭代器来遍历列表并显示内容。不幸的是,我的迭代器进入无限循环,我无法调试它。

这是代码 -如果您运行迭代器,您的浏览器将会崩溃 - 所有其他功能似乎都运行良好。

function List(){
this.listSize = 0;
this.pos = 0;
this.dataStore = [];
this.clearList = 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.currPos = currPos;
this.moveTo = moveTo;
this.getElement = getElement;
this.length = length;
this.contains = contains;
}

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

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

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

function length(){
return this.listSize;
}

function toString(){
return this.dataStore;
}

function insert(element, after){
var insertPos = this.find(after);
if(insertPos > -1){
this.dataStore.splice(insertPos+1,0,element);
++this.listSize;
return true;
}
return false;
}

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

function contains(element){
for(var i = 0; i < this.dataStore.length; ++i){
if(this.dataStore[i] == elemen){
return true;
}
}
return false
}


function front(){
this.pos = 0;
}

function end(){
this.pos = this.listSize-1;
}

function prev(){
if(this.pos > 0){
--this.pos;
}
}

function next(){
if(this.pos < this.listSize -1){
++this.pos;
}
}

function currPos(){
return this.pos;
}

function moveTo(position){
this.pos = position;
}

function getElement(){
return this.dataStore[this.pos];
}

var names = new List();
names.append("Clayton");
names.append("Raymond");
names.append("Cynthia");
names.append("Jennifer");
names.append("Bryan");
names.append("Danny");

names.front();
console.log(names.getElement());

names.next();
console.log(names.getElement());

names.next();
names.next();
names.prev();
console.log(names.getElement());


//iterator starts here
for(names.front(); names.currPos() < names.length(); names.next()){
console.log(names.getElement());
}

最佳答案

for 循环在 pos >= listSize 时终止。但是next()不会增加pos除非pos < listSize - 1 。一次pos == listSize - 1 , next()不会增加pos 。所以最大值poslistSize - 1 。因此循环永远不会终止。

关于javascript - 列表迭代器进入无限循环 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051875/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com