概念
- 如生活中的购物清单,待办事项,都是列表
- 元素不是很多
- 不需要很长序列查找或者排序
- 是最自然的数据组织方式
定义
- 列表是一组有序数据,每个列表中的数据成为元素,元素的数量受内存控制
- 不包含任何元素的列表称为空列表
- 具有迭代器,比
for 更加灵活
实现

代码实现
function List() { this.listLength = 0 this.pos = 0 this.dataStore = [] this.add = add this.delete = del this.find = find this.change = change this.getItem = getItem this.insert = insert this.next = next this.prev = prev this.clear = clearList this.getLength = getLength this.getPos = getPos // 下面是第一次写缺少的方法 this.toString = toString // 字符串返回当前list this.front = front // 直接到第一位 this.end = end //到最后一个元素位置 this.moveTo = moveTo //将当前位置移动到指定位置 this.contains = contains //是否包含该元素,我认为跟find是一样的… 噢,find如果是0为返回值不好判断了,职能单一原则,还是需要分离开}function add(ob) { this.dataStore[this.listLength++] = ob}function del(ob) { // 找 // 删 // 改指针 // 第一次实现忘了改 listLength var index = this.find(sourceObj) if (index > -1) { // 第一次用了 delete 数组用delete结果如下: // let arr = [1,2,3] // delete arr[2] // arr // (3) [1, 2, empty] // delete this.dataStore[index] this.dataStore.splice(index, 1) // 这样就能删掉了 // slice方法不会改变原数组, if (this.pos >= index) { this.pos-- } this.listLength-- return true } else { return false }}function find(obj) { for (let i = 0; i < this.listLength; i++) { if (obj == this.dataStore[i]) { return i } } // 第一次实现这里没有职能单一原则,返回了false,需要跟contain区分开 return -1}function change(sourceObj, targetObj) { var index = this.find(sourceObj) if (index) { this.dataStore.splice(index, 1, targetObj) return true } else { return false }}function getItem() { return this.dataStore[this.pos]}function insert(sourceObj, targetObj) { var index = this.find(sourceObj) if (index) { // 第一次实现index 没有 +1,需要+1 this.dataStore.splice(index + 1, 0, targetObj) // 第一次实现没有改变listLength this.listLength++ return true } else { return false }}function next() { // 第一次实现是小于 length -1 // 这样的问题就是迭代器到不了头 if (this.pos < this.listLength ) { this.pos++ return true } else { return false }}function prev() { if (this.pos != 0) { this.pos-- return true } else { return false }}function clearList() { this.dataStore = [] this.listLength = this.pos = 0}function getLength() { return this.listLength}function getPos() { return this.pos}function toString() { return this.dataStore}function front() { this.pos = 0}function end() { this.pos = this.listLength > 0 ? this.listLength - 1 : 0}function moveTo(index) { this.pos = index > this.listLength - 1 ? this.listLength : index}function contains(obj) { if (this.find(obj) > -1) { return true } return false}var list = new List()list.add('嘿嘿')list.add('吼吼')list.add('试试')var log = console.logvar warn = console.warnlog(list.listLength)log(list.getItem())log(list.next())log(list.getItem())log(list.find('试试'))if (list.find('试试')) { log('找到试试了, 我要把它变成不想试试') list.change('试试', '不想试试') log(list.find('不想试试'))}for (list.front(); list.getPos() < list.getLength() ; list.next()) { warn(list.getItem())}list.insert('吼吼', '在吼吼后面插入')for (list.front(); list.getPos() < list.getLength() ; list.next()) { warn(list.getItem())}