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]這樣的集合遇假值中斷的麻煩。