js下实现队列

来源:互联网 发布:参考文献 网络 编辑:程序博客网 时间:2024/05/16 08:48
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>dedicated web worker</title></head><body></body><script>    /*--------------Queue类的定义和测试代码----------------*/function Queue(){        this.dataStore = [];        this.enqueue = enqueue;        this.dequeue = dequeue;        this.front = front;        this.back = back;        this.toString = toString;        this.empty = empty;this.length=Length;}//入队,就是在数组的末尾添加一个元素function enqueue(element){    this.dataStore.push(element);}//出队,就是删除数组的第一个元素function dequeue(){    return this.dataStore.shift();}//取出数组的第一个元素function front(){    return this.dataStore[0];}//取出数组的最后一个元素function back(){    return this.dataStore[this.dataStore.length-1];}//取出数组的最后一个元素function Length(){    return this.dataStore.length;}function toString(){    var retStr = "";    for (var i=0; i<this.dataStore.length; ++i) {        retStr += this.dataStore[i] + " "    }    return retStr;}//判断数组是否为空function empty(){    if(this.dataStore.length == 0){        return true;    }else{        return false;    }    }//返回数组中元素的个数function count(){    return this.dataStore.length;}var q = new Queue();q.enqueue("Meredith");q.enqueue("Cynthia");q.enqueue("Jennifer");document.write(q.toString());document.write('<br>');document.write("Front of queue is:" + q.front()+" le "+q.length());console.log(q.dequeue()) ;console.log(q.length()) ;console.log(q.front()) ;document.write('<br>');document.write("Back of queue is:" + q.back());</script></html>