Array的栈方法和队列方法

一、栈数据结构 , LIFO ( Last-In-First-Out,后进先出 )的数据结构;

push() 方法可以接收任意数量的参数,把他们逐个添加到数组末尾,并返回修改后数组的长度;

pop() 方法则从数组末尾移除最后一项,减少数组的length值,然后返回移除的项;

 

二、队列数据结构,FIFO ( First-In-First-Out,先进先出 );

shift()方法,它能够移除数组中的第一个项并返回该项,同时将数组长度减1;

unshift()方法,它能在数组前端添加任意个项并返回新数组长度。

 

    var colors = ["black", "yellow"]; //创建新数组

    var count_push = colors.push("red", "green");  //在数组末尾添加两项
    console.log("push()后的colors数组:" + colors);  //black,yellow,red,green
    console.log("push()的返回值:" + count_push);  //4

    var item_pop = colors.pop();   //移除最后一项
    console.log("pop()后的colors数组:" + colors);  //black,yellow,red
    console.log("pop()的返回值:" + item_pop);  //green

    var count_unshift = colors.unshift("blue");  //在数组最前端添加一项
    console.log("unshift()后的colors数组:" + colors);  //blue,black,yellow,red
    console.log("unshift()的返回值:" + count_unshift);  //4

    var item_shift = colors.shift();   //移除第一项
    console.log("shift()后的colors数组:" + colors);  //black,yellow,red
    console.log("shift()的返回值:" + item_shift);  //blue

 

posted @ 2016-03-18 16:28  Kevin丶Z  阅读(274)  评论(0编辑  收藏  举报