第三章 列表

来源:互联网 发布:软件项目报价表 编辑:程序博客网 时间:2024/06/08 05:55

列表的抽象数据类型定义

属性/方法 描述 listSize(属性) 列表的元素个数 pos(属性 列表的当前位置 length(属性) 返回列表中元素的个数 clear(方法) 清空列表中的所有元素 toString(方法) 返回列表的字符串形式 getElement(方法) 返回当前位置的元素 insert(方法) front(方法) 将列表的当前位置设移动到第一个元素 end(方法) 将列表的当前位置移动到最后一个元素 prev(方法) 将当前位置后移一位 next(方法) 将当前位置前移一位 currPos(方法) 返回列表的当前位置 moveTo(方法) 将当前位置移动到指定位置

1. 通过构造函数定义 list 类

function list() {    this.listSize = 0;    this.pos = 0;    this.length = length;    this.dataStore = []; // 用来保存元素    this.find = find;    this.clear = clear;    this.insert = insert;    this.append = append;    this.remove = remove;    this.contains = contains;    this.toString = toString;    this.getElement = getElement;    this.front = front;    this.end = end;    this.prev = prev;    this.next = next;    this.currPos = currPos;    this.moveTo = moveTo;}

2. 分别实现clear,insert等方法。

1 find: 查找元素

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

注: 个人认为方法内部可以使用查找算法,提高查找效率。

2 clear:清除元素

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

注:对比勘误列表,修改此处。勘误列表地址

this.dataStore = []; 

this.dataStore.length = 0; 

原文解释如下:

Any reference to the List or to the datastore will contain the old values if this.dataSTore = [] is used.

示例如下:

var arr = [1, 2, 3];var arr1 = arr;arr = [];console.log(arr1); // [1, 2, 3]arr = [1, 2, 3];arr1 = arr;arr.length = 0;console.log(arr1); // []

3 insert: 插入元素到某一元素之后

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

4 append: 插入元素到末尾

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

5 remove: 移除某一元素

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

6 contains: 判断是否存在某一元素

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

7 toString: 返回列表数据

function toString() {    return this.dataStore;}

8 length: 返回列表元素个数

function length() {    return this.listSize;}

9 遍历列表: front, end, prev, next, getElement, currPos, moveTo

1 front: 移动当前位置到第一个元素
function front() {    this.pos = 0;}
2 end:移动当前位置到最后一个元素
function end() {    this.pos = this.listSize - 1;}
3 prev: 移动当前位置到前一个元素
function prev() {    if (this.pos > 0) {        this.pos--;    }}
4 next: 移动当前位置到后一个元素
function next() {    if (this.pos < this.listSize -1) {        this.pos++;    }}
5 currpos: 返回当前位置
function currPos() {    return this.pos;}
6 getElement: 返回当前位置的元素
function getElement() {    return this.dataStore[this.pos];}
7 moveTo: 移动到某一位置
function moveTo(pos) {    this.pos = pos;}