Javascript模拟c#中arraylist操作(学习分享)

最近在看javascript,在《javascript高级编程》中也学到了不少东西。但是在这里要感谢博客园的“汤姆大叔” 的无私奉献,他的关于javascript相关博文也给我了很大的帮助。在此同时也要感谢 博客园中的“阿蔡”,在我上篇随笔回复中提了相关建议!再次谢谢二位。

     在学习C#时候用到了ArrayList ,突然就想可不可以用javascript去模拟C#中ArrayList相关操作呢!C#中的ArrayList实例以后可以进行添加、移除、查找等操作。首先在此说明这个模拟操作的一些方法时候没有考虑执行效率相关问题,只是报着学习的态度去尝试。

  在此就分享相关代码,有什么不妥的地方希望各位高手斧正。谢谢。

/*

* javascript模拟C#中的arraylist
* 心伤烟雨

* QQ:909507090

* [url]www.qhjsw.net[/url]

* 更新时间:2012-02-24

*/

function ArrayList() {

this.length = 0;

this.array = new Array();

//获得指定索引的值
this.Item = function (index) {

return this.array[index];

}

//添加新项
this.Add = function (value) {

this.array[this.length] = value;


this.length++;

}

//移除
this.Remove = function (value) {

if (this.length >= 1) {

for (var i = 0; i < this.length; i++) {

if (this.array[i] == value) {

for (var j = i; j < (this.length - 1); j++) {

this.array[j] = this.array[j + 1];

}

this.length--;

this.array[this.length] = null;

this.array.length--;

break;

}

}

}

else {

this.length = 0;

}

}
//插入

this.Insert = function (value, index) {

if (index < 0) { index = 0; }


if ((this.length >= 1) && (index <= this.length)) {

for (var i = this.length; i > index; i--) {

this.array[i] = this.array[i - 1];

}


this.array[index] = value;


this.length++;

}

else {

this.Add(value);

}

}
//判断指定的值是否存在

this.Exist = function (value) {

if (this.length > 1) {

for (var i = 0; i < this.length; i++) {

if (this.array[i] == value) {

return true;

}

}

}


return false;

}

//清空
this.Clear = function () {
//感谢 “阿蔡” 的建议 谢谢 。
this.array.length = 0;

this.length = 0;

}


this.GetArray = function () {

return this.array;

}

//长度
this.Length = function () {

return this.length;

}

//导入
this.Import = function (splitString, splitChar) {

this.array = splitString.split(splitChar);


this.length = this.array.length;


}

//以指定分隔符导出,返回字符串
this.Export = function (joinChar) {

var strReturn = "";


if (this.length >= 1) {

for (var i = 0; i < this.length; i++) {

strReturn += this.array[i];


if (i < (this.length - 1)) {

strReturn += joinChar;

}

}

}

return strReturn;


}

}

如果有任何有助于我提高的还请各位大侠提出相关建议,我会加以学习和改正。希望共同与大家一起交流和学习。在此谢过。 

原文地址:https://www.cnblogs.com/bluescreen/p/2368216.html