JS基础--列表

列表

什么是列表?

列表是一组有序的数据。

什么时候使用列表?
  • 数据不多时
  • 不需要查找元素
  • 不需要排序
列表的抽象数据类型定义

列表的抽象数据类型定义

根据上面的表新建下面一个构造函数,后期还需要一些方法,用到的时候再去更新,现在下面一一的去实现:

function List() {
    this.listSize= 0;
    this.store= [];
    this.pos= 0;
    this.length= length;
    this.clear= clear;
    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.currPos= currPos;
    this.moveTo= moveTo;
}
  • 向列表添加元素
function append(ele) {
    this.store[this.listSize++] = ele;
}

这里的自加很巧妙

  • 从列表中删除元素

删除元素的思路是,先遍历列表找到这个元素的索引值,然后用splice方法删除它,元素个数减1,所以这里增加一个方法find,用于返回被查找元素的索引值。

function List() {
    ...
    this.find = find;
}

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

function remove(ele) {
    var num = this.find(ele);
    if (num > -1) {
    	this.store.splice(num, 1);
    	--this.listSize;
    }
}

  • 列表中有多少个元素
function length() {
    return this.listSize;
}
  • 显示列表中的元素

简单的返回一个数组

function toString() {
    return this.dataStore;
}
  • 向列表中插入一个元素

插入元素的思路是,插入的位置,这个位置也可以用find方法来返回这个索引值。

function insert(ele, where) {
	var num = this.find(where);
	if (num > -1) {
		this.store.splice(num, 0, ele);
		++this.listSize;
	}
}

  • 清空列表中所有的元素
function clear() {
	delete this.store;
	this.store = [];
	this.listSize = this.pos = 0;
}
  • 判断给定值是否在列表中

增加contains方法

function contains(ele) {
	for (var i = this.store.length - 1; i >= 0; i--) {
		if (this.store[i] === ele) {
			return true;
		}
	}
	return false;
}
  • 其它
function front() {
	this.pos = 0;
}


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

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

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

function currPos() {
	return this.pos;
}

function moveTo(num) {
	this.pos = num;
}
  • 返回列表的当前元素
function getElement() {
	return this.store[this.pos];
}

OK,到目前为止,方法都写完了,new 一个实例看看:

eg1 eg1