javascript數組是一個逆天的存在,到了ecma262v5,它已經是堆棧,列隊及迭代器的合體。有時候我們不需要這么強大的東西,這只要考慮到for循環太麻煩了,我們只需要非常簡單的遍歷,於是想用普通對象模擬一個就是。
首先是堆棧,先進后出
function Stack(){ } Stack.prototype = { add: function(el, pt){ this._first = pt = {//_first是不斷變的 _next:this._first, el: el } if (pt._next) { pt._next._prev = pt; } return this; } } var s = new Stack; s.add("1").add("2").add("3") var pt = s._first; while (pt) { alert(pt.el) pt = pt._next; }
接着是列隊,先進先出:
function Queue(){ } Queue.prototype = { add: function(el){ if( this._last ){ this._last = this._last._next = {//_last是不斷變的 el: el, _next: null//設置_last屬性表示最后一個元素,並且讓新增元素成為它的一個屬性值 } }else{ this._last = this._first = {//我們要設置一個_first屬性表示第一個元素 el: el, _next: null } } return this; } } var q = new Queue q.add("1").add("2").add("3") var pt = q._first; while (pt) { console.log(pt.el) pt = pt._next; }
由於這兩種結構的每個結點都是對象,因此它可以一直循環下去,直接_next為null。這樣就避免[1,0,null,2]這樣的集合遇假值中斷的麻煩。