天天看点

JS高级 05-02-04 Array类型 队列方法

栈数据结构的访问规则是LIFO(后进先出),而队列数据结构的访问规则是FIFO( First-In-First-Out, 先进先出)。队列在列表的末端添加项,从列表的前端移除项。由于push() 是向数组末端添加项的方法,因此要模拟队列只需一个从数组前端取得项的方法。实现这一操作的数组方法就是shift(),它能够移除数组中的第一个项并返冋该项,同时将数组长度减1。结合使用shift ()和push()方法,可以像使用队列一样使用数组。

var colors = new Array(); //create an array
var count = colors.push("red", "green"); //push two items
console.log(count); //2

count = colors.push("black"); //push another item on
console.log(count); //3

var item = colors.shift(); //get the first item
console.log(item); //"red"
console.log(colors.length); //2      

这个例子首先使用push()方法创建了一个包含3种颜色名称的数组。代码中加粗的那一行使用shift()方法从数组中取得了第一项,即“red”。在移除第一项之后,"green"就变成了第一项,而 "black"则变成了第二项,数组也只包含两项了。

ECMAScript还为数组提供了一个unshift ()方法。顾名思义,unshift()与shift()的用途相反: 它能在数组前端添加任意个项并返回新数组的长度。因此,同时使用unshift ()和pop()方法,可以从相反的方向来模拟队列,即在数组的前端添加项,从数纽末端移除项,如下面的例子所示。

var colors = new Array(); //create an array
var count = colors.unshift("red", "green"); //push two items
console.log(count); //2
count = colors.unshift("black"); //push another item on
console.log(count); //3
var item = colors.pop(); //get the first item
console.log(item); //"green"
console.log(colors.length); //2      

继续阅读