数组栈方法

栈是一种 LIFO(Last-In-First-Out,后进先出) 的数据结构,也就是最新添加的项最早被移除。而栈中项的插入(推入)和移除(弹出),只发生在一个位置——栈的顶部。ES为数组专门提供了push() 和 pop() 方法,以便实现类似栈的行为。
push();逐个添加到数组末尾,并返回修改后数组的长度。
pop(); 从数组末尾移除最后一项,减少数组的length值,让后返回移除的项。
请看下面例子

var colors = new Array(); //创建一个数组
var count = colors.push("red","green"); //推入两项
alert(count)//2

count = colors.push("black"); //推入另一项
alert(count)//3

var item = colors.pop(); //取得最后一项
alert(item); //"black"
alert(colors.length)//2

栈方法与其他数组方法连用

var colors=["red","green"];
colors.push("yellow");
colors[3] = "black";
alert(colors.length) //4

var item = colors.pop();
alert(item); //"black"

猜你喜欢

转载自blog.csdn.net/weixin_42549581/article/details/104151063