第三章(列表)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>實現列表類</title>
</head>
<body>
<script>
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.length=length;
this.contains=contains;
}
function append(element){//追加一個新的元素在列表裏
this.dataStore[this.listSize++]=element;
}
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 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 length(){
return this.listSize;
}
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){
++this.pos;
}
}
function currPos(){
return this.pos;
}
function moveTo(position){
this.pos=position;
}
function getElement(){
return this.dataStore[this.pos];
}
function createArr(file){
var arr=read(file).split("\n");
for(var i=0;i<arr.length;i++){
arr[i]=arr[i].trim();
}
return arr;
}
function Customer(name,movie){
this.name=name;
this.movie=movie;
}
function displatList(list){
for(list.front();list.currPos()<list.length()-1;list.next()){
if(list.getElement() instanceof Customer){
console.log(list.getElement()['name']+","+list.getElement()['movie']);
}
else{
console.log(list.getElement());
}
}
}
function checkOut(name,movie,filmList,customerList){
if(moveList.contains(movie)){
var c=new Customer(name,movie);
customerList.append(c);
filmList.remove(c);
}
else{
console.log(movie+" is not avaliable");
}
}
var names=new List();
names.append('Cyssa1');
names.append('Cyssa2');
names.append('Cyssa3');
names.append('Cyssa4');
names.append('Cyssa5');
names.append('Cyssa6');
console.log(names.length());
for(names.front();names.currPos()<names.length();names.next()){
console.log(names.getElement());
}
</script>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章