javascript顺序表

<!doctype html>
<head>
	<meta charset = "utf-8" />
</head>

<body>
	<script>
		//顺序表对象
		function SeqList(){
			const maxSize = 100; //顺序表最大容量
			//私有成员变量
			let data = new Array(maxSize); //存放数据的数组
			let length = 1;  //顺序表的长度
			//构造函数的参数初始化
			(function(args){
				let len = args.length;
				try{
					if(len == 0){
						console.log(length);
						length = 0;
					}else if(args[0] instanceof Array){
						let arr = args[0];
						length = arr.length;
						if(length > maxSize) throw "顺序表不能超过" + maxSize;
						for(let i = 0; i<length; i++)
							data[i] = arr[i];
					}else{
						throw "传递的参数有误";
					}
					}catch(err){
						console.log(err);
					}
			})(arguments);
			//公有成员方法
			//按位读取 i表示第几个元素,不是下标,不从0开始
			this.getValue = function(i){
				try{
					if(i < 1 || i > length) 
						throw "查找位置非法";
					else 
						return data[i-1];
				}catch(err){
					console.log(err);
				}
			}
			//按值查找 返回对应序号,不是下标
			this.getIndex = function(value){
				for(let i=0; i<length;i++)
					if(data[i] == value)
						return ++i;
				return false;		
			}
			//插入 插入的序号和值
			this.insert = function(i,value){
				try{
					//判断是否溢出
					if(length >= maxSize) throw "顺序表已满"; 
					if(i<1 || i>length) throw "插入位置不对";
					//先把后面元素后移1位,再插入
					for(let j = length; j>=i; j--)
						data[j] = data[j-1];
					data[i-1] = x;	
					length++;
				}catch(err){
					console.log(err);
				}
			}
			//删除 
			this.delete = function(i){
				try{
					if(length == 0) throw "顺序表为空";
					if(i<1 || i>length) throw "删除位置不对";
					//去除被删除元素
					let x = data[i-1];
					for(let j = i; j<length; j++){
						data[j-1] = data[j];
					}
					length--;
					return x;
				}catch(err){
					console.log(err);
				}
			}
			//遍历
			this.printList = function(callback){
				for(let i=0; i<length; i++){
					callback.call(this,i+1,data[i]);
				}
			}
		}
		let arr = [1,2,3,4,5,6,7,8,9];
		let seqList = new SeqList(arr);
		seqList.printList(function(index,value){
			console.log("顺序表第" + index + "个元素是:" + value);
		});
	</script>
</body>

</html>

  

posted @ 2018-04-19 09:49  web_小隆  阅读(178)  评论(0编辑  收藏  举报