Hello小伙伴们~上次分享有小伙伴在后台留言说程序就是一个数据结构,怎么说呢,我觉得这是片面的,在生产中,我们往往会尽量避免在前端写业务逻辑,因为有些不安全,而且也比较影响性能,确实离不开数据结构,但是呢也不能完全说这二者相同啦~兔妞是这样理解的,如果理解的有问题还请后台留言,帮助改正哦~闲话不多说,开始今天的列表吧~
列表
不知道大家有没有习惯做什么之前列一个to do list,反正列表是充斥在兔妞生活中的各处,购物列表、待办列表。。。我们就来详细介绍一下列表这个数据结构吧!
1) 列表是什么呢?
列表是一组有序的数据。每个列表中的数据项称为元素。JS中,列表中的元素可以是任何数据类型,列表中可以保存多少元素并没有事先设定,实际使用时元素的数量受到程序内存的限制。列表甚至也可以是空的。
2)定义列表类
function list(){
this.listSize=0;
this.pos=0;
this.dataStore=[];
this.clear=clear;
this.find=find;
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.length=length;
this.currPos=currPos;
this.moveTo=moveTo;
this.getElement=getElement;
this.contains=contains;
}
function append(ele){
this.dataStore[this.listSize++]=ele;
}
function find(element) {
for (var i = 0; i < this.dataStore.length; ++i) {
if (this.dataStore[i] == element) {
return i;
}
}
return -1;
}
function remove(element) {
var foundAt = this.find(element);
if (foundAt > -1) {
this.dataStore.splice(foundAt,1);
--this.listSize;
return true;
}
return false;
}
function length() {
return this.listSize;
}
function toString() {
return this.dataStore;
}
function insert(element, after) {
var insertPos = this.find(after);
if (insertPos > -1) {
this.dataStore.splice(insertPos+1, 0, element);
++this.listSize;
return true;
}
return false;
}
function clear() {
delete this.dataStore;
this.dataStore = [];
this.listSize = this.pos = 0;
}
function contains(element) {
for (var i = 0; i < this.dataStore.length; ++i) {
if (this.dataStore[i] == element) {
return true;
}
}
return false;
}
function front() {
this.pos = 0;
}
function end() {
this.pos = this.listSize-1;
}
function prev() {
if (this.pos > 0) {
--this.pos;
}
}
function next() {
if (this.pos < this.listSize-1) {
++this.pos;
}
}
function currPos() {
return this.pos;
}
function moveTo(position) {
this.pos = position;
}
function getElement() {
return this.dataStore[this.pos];
}
3)列表的特点
看过了上面的实现,大家应该发现了,列表中包含元素的个数称为length,可以获取某元素后的元素,可以对元素进行增删操作:可以remove可以insert。而且列表具有描述元素位置的属性,即前后,也可以将元素向前或向后移动。
好啦,今天的分享就到这里啦,喜欢的小伙伴请关注+好看吧~~