数据结构基础——队列

107 阅读1分钟

队列的特点

  • 先进先出

在JavaScript中使用数组来模拟队列

使用队列的场景

  • JS异步中的任务队列
  • 计算最近请求次数

队列的典型习题

实现代码

var RecentCounter = function () {
    this.arr = [];
    this.result = [];
};


RecentCounter.prototype.ping = function (t) {

    // 新ping的元素入队
    this.arr.push(t);
    while (this.arr[0] < t - 3000) {
        this.arr.shift();
    }

    return this.arr.length;
};