JS数组栈方法和队列方法

Array类型的调整数组数量的几个方法

常见的有以下几个:javascript

  • push()方法
  • pop()方法
  • shift()方法
  • unshift()方法

push()方法和pop()方法:

push()方法可接受不了任意数量的参数,把它们逐个添加到数组末尾,并返回修改后的参数;pop()方法会从数组的末尾删除掉最后一项,并返回被移除的值前端

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);
alert(colors.length);

上面一段代码会添加数组的最后一项,并移除最后一项,这段代码能够当作一个栈,值得注意的是,若是用其余的方法,使得数组中间有"空位"的话,中间的空位会被设置成undefined数据类型。以下:java

var colors=["red","blue"];
        colors[3]="black";
        colors.push("brown");
        alert(colors[2]);

代码第二行:当数组的第四位被设置成"black"的时候,第三位并无值,而使用push()方法则会直接添加到最后一位(即第五位),而第三位则会是undefined。数组

shift()方法和unshift()方法:

shift()方法可移除数组中的第一个项,并返回该项;unshift()方法看起来向反,它能在数组前端添加任意个项,并返回数组新的长度code

var colors=new Array();
var count=colors.unshift("red","green");
alert(count);  //2
count=colors.unshift("black");
alert(count);  //3
var item=colors.pop();
alert(item);  //green
alert(colors.length);  //2
相关文章
相关标签/搜索