本文介紹了一個用 JavaScript 模擬 C# 中 List(大小可變數組)的實現,需要的朋友可以參考,希望對大家有所幫助。
<script> /* * List 大小可變數組 * version: 1.0 */ function List() { this.list = new Array(); }; /** * 將指定的元素添加到此列表的尾部。 * @param object 指定的元素 */ List.prototype.add = function(object) { this.list[this.list.length] = object; }; /** * 將List添加到此列表的尾部。 * @param listObject 一個列表 */ List.prototype.addAll = function(listObject) { this.list = this.list.concat(listObject.list); }; /** * 返回此列表中指定位置上的元素。 * @param index 指定位置 * @return 此位置的元素 */ List.prototype.get = function(index) { return this.list[index]; }; /** * 移除此列表中指定位置上的元素。 * @param index 指定位置 * @return 此位置的元素 */ List.prototype.removeIndex = function(index) { var object = this.list[index]; this.list.splice(index, 1); return object; }; /** * 移除此列表中指定元素。 * @param object 指定元素 * @return 此位置的元素 */ List.prototype.remove = function(object) { var i = 0; for(; i < this.list.length; i++) { if( this.list[i] === object) { break; } } if(i >= this.list.length) { return null; } else { return this.removeIndex(i); } }; /** * 移除此列表中的所有元素。 */ List.prototype.clear = function() { this.list.splice(0, this.list.length); }; /** * 返回此列表中的元素數。 * @return 元素數量 */ List.prototype.size = function() { return this.list.length; }; /** * 返回列表中指定的 start(包括)和 end(不包括)之間列表。 * @param start 開始位置 * @param end 結束位置 * @return 新的列表 */ List.prototype.subList = function(start, end) { var list = new List(); list.list = this.list.slice(start, end); return list; }; /** * 如果列表不包含元素,則返回 true。 * @return true or false */ List.prototype.isEmpty = function() { return this.list.length == 0; }; </script>這個封裝通過原型方法為 List 提供了 add(尾部添加)、addAll(合併列表)、get(按下標取值)、removeIndex(按位置刪除)、remove(按元素刪除)、clear(清空)、size(取長度)、subList(截取子列表)與 isEmpty(判斷是否為空)等操作,基本對齊了 C# List 的常用 API。對於習慣了 C# 的開發者來說,這樣的封裝能讓 JS 中的集合操作更加順手。