队列

  • 一个先进先出的数据结构
  1. const queue = [];
  2. stack.push(1);
  3. stack.push(2);
  4. const item1 = stack.shift();
  5. const item2 = stack.shift();

什么场景下使用队列

需要先进先出的场景

  • 食堂排队打饭
    1. js是单线程,无法同时处理异步中的并发任务
    2. 使用任务队列先后处理异步任务
  • 计算最近请求次数

计算最近请求次数

  1. let time = [null,[1],[200],[3001],[3002]];
  2. let recentCounter = function(){
  3. this.q = []
  4. }
  5. recentCounter.prototype.ping = function(t){
  6. this.q.push(t);
  7. while(this.q[0] < t - 3000){
  8. this.q.shift()
  9. }
  10. return this.q.length
  11. }

JS异步中的任务队列

数据结构-队列 - 图1