The Javascript array is a forward-to-day existence. To ecma262v5, it is already a combination of stacks, queues, and iterators. Sometimes we don't need such a powerful thing. Considering that the for loop is too troublesome, we only need a very simple traversal, so we want to simulate one with a common object.
The first is the stack.
Function stack () {} stack. prototype = {Add: function (El, pt) {This. _ first = Pt = {// _ first is constantly changing _ 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 ;}
The next step is queuing, first-in-first-out:
function Queue () {} queue. prototype = {Add: function (EL) {If (this. _ last) {This. _ last = This. _ last. _ next = {// _ last is the constantly changing El: El, _ next: NULL // sets the _ last attribute to represent the last element, and make the new element a property value} else {This. _ last = This. _ first = {// we need to set a _ first attribute to indicate the first element 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 ;}
since each node of the two structures is an object, it can continue to loop, and the direct _ next is null. This avoids the trouble of interruption of false values in a set such as [1, 0, null, 2.