当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS使用数组实现的队列功能示例

JS使用数组实现的队列功能示例

2019年05月28日  | 移动技术网IT编程  | 我要评论

本文实例讲述了js使用数组实现的队列功能。分享给大家供大家参考,具体如下:

/*一个用数组实现的队列*/
function queue(){
  this.datastore = [];//存放队列的数组,初始化为空
  this.enqueue = enqueue;//向队列尾部添加一个元素
  this.dequeue = dequeue;//删除队首的元素
  this.thefront = thefront;//读取队首的元素
  this.back = back;//对取队尾的元素
  this.tostrings = tostrings;//显示队列内的所有元素
  this.empty = empty;//判断队列是否为空
}
function enqueue(element){
  this.datastore.push(element);
}
function dequeue(){
  this.datastore.shift();
}
function thefront(){
  return this.datastore[0];
}
function back(){
  return this.datastore[this.datastore.length-1];
}
function tostrings(){
  return this.datastore;
}
function empty(){
  if(this.datastore.length == 0){
    return true;
  }else{
    return false;
  }
}
/*测试程序*/
var q = new queue();
q.enqueue("aa");
q.enqueue("bb");
q.enqueue("cc");
console.log(q.tostrings());//[ 'aa', 'bb', 'cc' ]
q.dequeue();
console.log(q.tostrings());//[ 'bb', 'cc' ]
console.log(q.thefront());//bb
console.log(q.back());//cc

这里使用在线html/css/javascript代码运行工具:测试上述代码,可得如下运行结果:

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript数据结构与算法技巧总结》、《javascript数学运算用法总结》、《javascript排序算法总结》、《javascript遍历算法与技巧总结》、《javascript查找算法技巧总结》及《javascript错误与调试技巧总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网