天天看点

JS高级 05-02-03 Array类型 栈方法

ECMAScript数组也提供了一种让数组的行为类似于其他数据结构的方法。具体说来,数组可以表现得就像栈一样,后者是一种可以限制插人和删除项的数据结构。栈是一种LIFO (Last-In-First-Out, 后进先出)的数据结构,也就是最新添加的项最早被移除。而栈中项的插入(叫做推入)和移除(叫做 弹出),只发生在一个位置——栈的顶部。ECMAScript为数组专门提供了 push() 和pop()方法,以便实现类似栈的行为。

push()方法可以接收任意数量的参数,把它们逐个添加到数组末尾,并返回修改后数组的长度。而 pop()方法则从数组末尾移除最后一项,减少数组的length值,然后返回移除的项。请看下面的例子:

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.pop(); //get the last item
console.log(item); //"black"
console.log(colors.length); //2      

以上代码中的数组可以看成是栈(代码本身没有任何区别,而push()和pop()都是数组默认的方法)。首先,我们使用push() 将两个字符串推入数组的末尾,并将返回的结果保存在变量count中(值为2)。然后,再推入一个值,而结果仍然保存在count中。因为此时数组中包含3项,所以push() 返回3。在调用pop()时,它会返回数组的最后一项,即字符串"black"。此后,数组中仅剩两项。

var colors = ["red", "blue"];
colors.push("brown"); //add another item
colors[3] = "black"; //add an item
console.log(colors.length); //4

var item = colors.pop(); //get the last item
console.log(item); //"black"      

继续阅读