方法一:利用两个栈实现队列
let stack1 = [], //两个数组模拟栈的行为 stack2 = []; function push(node) { //栈是后入先出(LIFO),队列是先入先出(FIFO) while (stack2.length !== 0) { stack1.push(stack2.pop()); } stack1.push(node); } function pop() { while (stack1.length !== 0) { stack2.push(stack1.pop()); } return stack2.pop(); } push(0); push(1); push(2); push(3); console.log(pop()); console.log(pop()); console.log(pop()); console.log(pop());
方法二:
observal = { callback: [], add: function(node){ this.callback.push(node) }, fire: function(){ this.callback.forEach(function(node){ console.log(node); }) } } observal.add(0); observal.add(1); observal.add(2); observal.add(3); observal.fire();