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) {
console.log(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;
}
本文轉載自 http://www.cnblogs.com/rubylouvre/archive/2012/11/23/2785051.html