js队列方法push()、shift()与pop()、unshift()的理解

来源:互联网 发布:快阅读软件 编辑:程序博客网 时间:2024/05/23 13:03

队列:先进先出;

在学习js的过程中,碰到这样一个问题:


var colors=new Array();

 var count=colors.unshift("red","green");    //推入多个项

count=colors.unshift("black");                  //推入单个项

var item=colors.pop();                              //移除

alert(item);                  //''green''

我的问题是:为什么移除的是 green而不是red 呢?本人仔细又回去看了一下数据结构,了解下面概念就不难理解了;

1、push()是用来在数组末端添加项,shift()在移除数组的第一个项(前端);

2、pop()在数组末端移除项,unshift()在数组前端添加项;

3、push(),unshift()在推入多个项时,各个项之间的顺序不变

4、push(),unshift()将数组的长度+1并返回的是数组的长度,pop(),shift()将数组length-1并返回的是移除的项

例如:

var num=new Array();

num.push("1","2","3");  //推入项 数组呈现为①②③

console.log(num.shift());//移除①项,数组呈现为②③

num.unshift(''4''); //在前端添加项,数组呈现为④②③

num.push("5"); //在末端添加项,数组呈现为④②③⑤

console.log(num.shift());//移除数组的第一个项,验证得到④

num.unshift("6","7","8"); //注意这里,以及下一句 数组呈现为⑥⑦⑧②③⑤

num.push("9","10");   //数组呈现为⑥⑦⑧②③⑤⑨⑩


0 0