Created
December 20, 2012 13:46
-
-
Save lyuehh/4345404 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* array_list | |
*/ | |
'use strict'; | |
function ArrayList() { | |
this.data = []; | |
this.length = 0; | |
} | |
ArrayList.prototype = { | |
constructor: ArrayList, | |
append: function (item) { | |
this.data[this.length] = item; | |
this.length ++; | |
}, | |
remove2: function (index) { | |
this.check(index); | |
var item = this.data[index]; | |
this.data.splice(index,1); | |
this.length --; | |
return item; | |
}, | |
remove: function (index) { | |
this.check(index); | |
var item = this.data[index]; | |
for (var i = index; i < this.data.length; i += 1) { | |
this.data[i] = this.data[i+1]; | |
} | |
// TODO js删除数组元素只能用splice方法,不存在的元素是undefined | |
// this.data.splice(this.length,1); // 这一句话没作用?? | |
this.length --; | |
return item; | |
}, | |
size: function () { | |
return this.length; | |
}, | |
insert2: function (index, item) { | |
this.check(index); | |
this.data.splice(index, 0, item); | |
this.length ++; | |
}, | |
insert: function (index, item) { | |
this.check(item); | |
for (var i = this.length; i >= index; i -= 1) { | |
this.data[i] = this.data[i-1]; | |
} | |
this.data[index] = item; | |
this.length ++; | |
}, | |
check: function (index) { | |
if(typeof index !== 'number') { | |
throw 'index should be number'; | |
} | |
if(index < 0 || index > this.length) { | |
throw 'index should large than 0 and less than this.size()'; | |
} | |
} | |
}; | |
module.exports = ArrayList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment