1. 程式人生 > >js高級程序設計數組的一些方法

js高級程序設計數組的一些方法

RR 前端 gree 數據 後進先出 數據結構 數組 tro gre

數組的棧方法:

棧是一種 LIFO(Last-In-First-Out, 後進先出)的數據結構,也就是最新添加的項最早被移除。

而棧中項的插入(叫做推入)和移除(叫做 彈出),只發生在一個位置——棧的頂部。

ECMAScript 為數組專門提供了 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 

 push()返回的是數組現在的長度,pop()返回的是從數組被去除的那一項

隊列方法

隊列數據結構的訪問規則是 FIFO(First-In-First-Out, 先進先出)。隊列在列表的末端添加項,從列表的前端移除項。

結合使用 shift()和 push()方法,可以像使 用隊列一樣使用數組。

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

代碼中加粗的那一行使用 shift()方法從數組中取得了第一項,即"red"

ECMAScript 還為數組提供了一個 unshift()方法。顧名思義,unshift()與 shift()的用途相反: 它能在數組前端添加任意個項並返回新數組的長度。因此,同時使用 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

總結:

push()從數組末端推入 返回的是數組長度

pop()從數組末端取出 返回取出的那一項

shift()從數組前端取出 返回取出的那一項

unshift()從數組末端推入 返回的是數組長度

js高級程序設計數組的一些方法