Javascript:Array.prototype 的使用
RojerChen.2013.01.29
最近專案都在寫 JS,在處理陣列的時候有內建的 PUSH、POP、SPLICE 等功能可以來取得、刪除資料,只不過當我要把資料刪除、插入等等功能好像就沒有提供得很完整,所以就需要稍微客製化一下!
首先我們先來看 W3C 對於 Array Prototype 的說明:
Definition and Usage
The prototype constructor allows you to add new properties and methods to the Array() object.
When constructing a property, ALL arrays will be given the property, and it's value, as default.
When constructing a method, ALL arrays will have this method available.
Note: Array.prototype does not refer to a single array, but to the Array() object itself.
Note: Prototype is a global object constructor which is available for all JavaScript objects.
Array.prototype.add = function (obj) { this.push(obj); } //插入一筆資料 Array.prototype.Insert = function (index, obj) { this.splice(index, 0, obj); } //清除資料 Array.prototype.RemoveAll = function () { this.splice(0, this.length); }客製化完畢後,當我往後有用到 Array 的時候,就可以使用這些方法了!
var list; list = new Array(); olist = new Object(); olist.name = "name1"; olist.id = 1; list.add(olist); olist = new Object(); olist.name = "name3"; olist.id = 3; list.add(olist); //從中插入一筆資料,讓資料順序變成 name1、name2、name3 olist = new Object(); olist.name = "name2"; olist.id = 2; list.Insert(1, olist); //清除所有資料 list.RemoveAll();
其他關於 JS Array 的使用可以參考一下這一篇,還蠻詳盡的: Javascript Core Object 陣列物件
0 意見:
張貼留言