function List(len, initData) {
if (!initData)
initData = []
if ( !(initData instanceof Array) )
throw 'initData为数组'
if (len < initData.length)
throw 'initData初始数据过长'
this.len = len
this._list = new Array(len)
this.init(initData)
}
List.prototype = {
init: function(initData) {
for (var i in initData) {
this._list[i] = initData[i]
}
},
delIndex: function(i) {
if (i <= 0)
throw 'i不能为负数'
if (i > this.len)
throw 'i不能大于线性表长度'
if (this.len === 0)
throw '当前为空'
var val = this._list[i]
this.len --
this._list.length = this.len
for (var j = i; j < this.len; j++)
this._list[j] = this._list[j + 1]
return val;
},
delValue: function(val) {
var idx = this.getIndex(val)
return this.delIndex(idx)
},
insert: function(i, val) {
if (i <= 0)
throw 'i不能为负数'
if (i > this.len)
throw 'i不能大于线性表长度'
this.len ++
for (var j = this._list.length; j > i; j--)
this._list[j] = this._list[j - 1]
this._list[i] = val;
},
getIndex: function(val) {
var index = -1
for (var i = 0; i < this.len; i++) {
if (this._list[i] === val) {
index = i
break;
}
}
return index
},
getValue: function(i) {
return this._list[i]
},
getList() {
return this._list
}
}
var l = new List(20, [1, 2, 3, 4, 5, 6, 7, 8, 9])
console.log(l.getList())
l.insert(2, 22)
console.log(l.getList())
console.log(l.getIndex(22))
console.log(l.getValue(2))
l.delValue(22);
console.log(l.getList())
l.delIndex(2);
console.log(l.getList())