zoukankan      html  css  js  c++  java
  • 【js】栈方法和队列方法

    栈方法:后进先出,推入(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); //"black"
    alert(colors.length); //2

    队列方法:先进先出;shift()移除数组中第一项并返回该项,同时将数组长度减1.结合使用shift()和push()方法,可以像使用队列一样使用数组。还有unshift()方法,在数组的前端添加任意个项并返回新数组的长度。

    var colors = new Array(); //创建一个数组
    var count = colors.push("red", "green"); //推入两项
    alert(count); //2
    count = colors.push("black"); //推入另一项
    alert(count); //3
    var item = colors.shift(); // 取得第一项
    alert(item); //"red"
    alert(colors.length); //2

    同时使用 unshift() 和 pop() 方法,可以从相反的方向来模拟队列,即在数组的前端添加项,从数组末端移除项,如下面的例子所示:

    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

  • 相关阅读:
    mysql 查询当天、本周,本月,上一个月的数据
    Mysql 查看连接数,状态 最大并发数,以及设置连接数
    MySQL慢查询日志优化
    java中线程通信(传统的线程通信)
    java中死锁
    同步锁(lock)
    同步锁(lock)
    释放同步监视器的锁定(java疯狂讲义)
    linux第9天 UDP
    linux第8天 connect强化
  • 原文地址:https://www.cnblogs.com/xiaoyujade/p/6911702.html
Copyright © 2011-2022 走看看