javascript中的栈、队列

栈方法

    栈是一种LIFO(后进先出)的数据结构,在js中实现只需用到2个函数

     push()  接受参数并将其放置数组尾,并返回修改后的数组长度。

     pop()  移除数组尾的最后一项,并返回移除项的值。

事例:

var colors = new Array();
var count = colors.push("red","green");
count = colors.push("block");   //在数组尾插入“block”元素
alert(count); //3 //数组的长度为3

  

var item = colors.pop();     //移除数组尾的一个元素
alert(item); //block //返回移除的值为“block”
alert(colors.length); //2 //数组的长度为2

 

队列方法         栈是一种FIFO(先进先出)的数据结构,在js中实现也只需用到2个函数

一个是上面的push()函数,另一个是shift()

shift() 移除数组尾的第一项,并返回移除项的值。

其方法只需将上面的pop方法改为shift即可

 

var rem = colors.shift();      //移除数组头的一个元素
alert(rem); //red //返回移除的值“red”
alert(colors.length);//2 //数组的长度为2

 

相关文章:

  • 2021-06-02
  • 2022-01-19
  • 2021-08-23
  • 2021-11-03
  • 2022-01-08
  • 2022-12-23
  • 2021-05-19
  • 2021-07-22
猜你喜欢
  • 2021-05-29
  • 2022-01-04
  • 2022-03-02
  • 2021-07-27
  • 2021-08-08
  • 2021-07-02
  • 2022-12-23
相关资源
相似解决方案