- 列表是一组有序的数据
- 列表中的元素可以是任意数据类型
- 列表拥有描述元素位置的属性
- 列表的存储结构可以是任意,比如是数组
function List() {
this.listSize = 0;
this.pos = 0;
this.dataStore = [];
this.clear = clear;
this.find = find;
this.toString = toString;
this.insertBefore = insertBefore;
this.insertAfter = insertAfter;
this.append = append;
this.remove = remove;
this.front = front;
this.end = end;
this.prev = prev;
this.next = next;
this.currPos = currPos;
this.moveTo = moveTo;
this.getElement = getElement;
this.length = length;
this.contains = contains;
}
// 清空列表元素
var clear = function() {
this.dataStore = [];
this.listSize = this.pos = 0;
};
// 查询列表元素
var find = function(value) {
return this.dataStore.indexOf(value);
};
// 返回列表字符串格式
var toString = function() {
return this.dataStore.toString();
};
// 往指定元素前插入元素
var insertBefore = function(insertVal, beforeVal) {
var _pos = this.find(beforeVal);
if (_pos == -1) {
return;
}
this.dataStore.splice(_pos, 0, insertVal);
++this.listSize;
return true;
};
// 往指定元素后插入元素
var insertAfter = function(insertVal, afterVal) {
var _pos = this.find(afterVal);
console.log;
if (_pos == -1) {
return;
}
this.dataStore.splice(_pos + 1, 0, insertVal);
++this.listSize;
return this.dataStore;
};
// 往列表末尾添加元素
var append = function(value) {
this.dataStore.push(value);
++this.listSize;
return this.dataStore;
};
// 移除指定元素
var remove = function(value) {
var _pos = this.find(afterVal);
if (_pos == -1) {
return;
}
this.dataStore.splice(_pos, 1);
--this.listSize;
return this.dataStore;
};
// 将列表当前位置移到第一个元素
var front = function() {
this.pos = 0;
};
// 将列表当前位置移到最后一个元素
var end = function() {
this.pos = this.listSize - 1;
};
// 当前位置前进一位
var prev = function() {
if (this.pos > 0) {
--this.pos;
}
};
// 当前位置后退一位
var next = function() {
if (this.pos < this.listSize - 1) {
++this.pos;
}
};
// 当前位置
var currPos = function() {
return this.pos;
};
// 当前位置移动到指定位置
var moveTo = function(position) {
this.pos = position;
};
// 获取当前位置的元素
var getElement = function() {
return this.dataStore[this.pos];
};
// 获取列表个数
var length = function() {
return this.listSize;
};
// 是否包含当前元素
var contains = function(value) {
return this.dataStore.indexOf(value) === -1 ? false : true;
};
var list = new List();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.append(5);
console.log(list.length());
console.log(list.contains(5));
console.log(list.getElement());
list.moveTo(2);
console.log(list.currPos());
console.log(list.getElement());
list.next();
console.log(list.getElement());
list.end();
console.log(list.getElement());
list.insertAfter(6, 5);
list.end();
console.log(list.getElement());
list.front();
console.log(list.getElement());