小理论:
队列:先进先出
堆栈:后进先出
实现队列的方法:
shift:从集合中把第一个元素删除,并返回这个元素的值。
unshift: 在集合开头添加一个或更多元素,并返回新的长度
push:在集合中添加元素,并返回新的长度
pop:从集合中把最后一个元素删除,并返回这个元素的值。
这是原来老赵写的关于数组队列的代码,觉得有点问题,所以改了一下
1 // Usage:装载并运行函数
2 // 队列机制
3 var Resource = (function () {
4 var waitingCallbacks = []
5 var execute = function (cb) {
6 setTimeout(function () {
7 cb(function () {
8 if (waitingCallbacks.length == 0) return
9 execute(waitingCallbacks.shift())
10 })
11 }, 0)
12 }
13 var register = function (cb) {
14 if (waitingCallbacks.length == 0) {
15 execute(cb)
16 } else {
17 waitingCallbacks.push(cb)
18 }
19 }
20 return {
21 register: register,
22 state: 1
23 }
24 })()
原来代码中是
execute(waitingCallbacks.unshift())现在我改成了
execute(waitingCallbacks.shift())当你从集合中执行了函数后,它应该从集合中删除,而不是再添加,呵呵。
push(E item)Pushes an item onto the top of this stack.
public boolean add(E e)
Appends the specified element to the end of this Vector.