简体   繁体   中英

Best way to implement a queue in javascript?

Hi I want to use a queue in javascript. So I guess I can do 1 of 3 things:

  1. javascript push, shift

  2. array.push(), array[0], array.splice(0,1) etc.

  3. Queue.js at http://code.stephenmorley.org/javascript/queues/#download

So I was reading the queue.js and was confused about the benchmarks because I don't really know what the numbers mean. Also, I'm guessing there are better ways of doing a queue than the 3 I mentioned.

So what's the best way of implementing a queue in javascript and why? Also if anyone could explain the advantages and disadvantages among the 3 ways I described, that would be very helpful. Thanks !

Here is a basic Queue definition, which works just perfectly for me.

queue: function() {
    var items;

    this.enqueue = function(item) {
        if (typeof(items) === 'undefined') {
            items = [];   
        }

        items.push(item);                       
    }

    this.dequeue = function() {
        return items.shift();                                                
    }

    this.peek = function(){
        return items[0];                  
    }
}

Queue.js is using something like your second proposition but it's less efficient because it requires unneeded tests, native methods are better optimized. I would definitively use Sacket's solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM