List 抽象数据类型定义列表是一组有序的数据。每个列表中的数据项称为元素。在 Javascript 中,列表中的元素可以是任意数据类型。
我们可以根据数组的特性来实现List。
listSize(属性) 列表的元素个数
pos(属性) 列表的当前位置
length(属性) 返回列表中元素的个数
clear(方法) 清空列表中的所有元素
toString(方法) 返回列表的字符串形式
getElement(方法) 返回当前位置的元素
insert(方法) 在现有元素后插入新元素
append(方法) 在列表的末尾添加新元素
remove(方法) 从列表中删除元素
front(方法) 将列表的当前位置设移动到第一个元素
end(方法) 将列表的当前位置移动到最后一个元素
prev(方法) 将当前位置前移一位
next(方法) 将当前位置后移一位
currPos(方法) 返回列表的当前位置
moveTo(方法) 将当前位置移动到指定位置
class List{ constructor() { this.dataSouce = []; this.listSize = 0; // 列表的大小
this.pos = 0; // 列表中当前的位置
}
append(element) { this.dataSouce[this.listSize++] = element;
}
insert(element) { this.dataSouce.push(element); this.listSize++;
}
remove(element) { // 查找当前元素的索引
const index = this.dataSouce.indexOf(element); if (index >= 0) { this.dataSouce.splice(index, 1); this.listSize--; return true;
} return false;
}
contains(element) { return this.dataSouce.indexOf(element) > -1;
}
front() { this.pos = 0;
}
end() { this.pos = this.listSize - 1;
}
prev() { if (this.pos > 0) {
--this.pos;
}
}
next() { if (this.pos <= (this.listSize - 1)) {
++this.pos;
}
}
currPos() { return this.pos;
}
moveTo(position) { this.pos = position;
}
getElement() { return this.dataSouce[this.pos];
}
clear() { delete this.dataSouce; this.dataSouce = [];
tihs.listSize = 0; this.pos = 0;
}
length() { return this.listSize;
}
toString() { return this.dataSouce;
}
}export default List;原文出处:https://www.cnblogs.com/qiaojie/p/9571990.html



