JS数组栈方法和队列方法

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

常见的有如下几个:

  • 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数据类型。如下:

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

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

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

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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值