JavaScript數組的棧方法與隊列方法詳解_javascript技巧

來源:互聯網
上載者:User

數組(Array)和對象(Object)應該是JavaScript中使用最多也是最頻繁的兩種類型了,Array提供了很多常用的方法:棧方法、隊列方法、重排序方法、操作方法、位置方法、迭代方法等等。

1、Array的棧方法

棧是一種LIFO(Last-In-First-Out,後進先出)的資料結構,也就是最新添加的項最早被移除。棧中項的插入(push)和移除,只發生在一個位置——棧的頂部。ECMAScript為數組提供了push()和pop()方法,可以實作類別似棧的行為。下面兩圖分別示範了入棧與出棧操作。

push()方法可以接收任意資料的參數,把它們逐個添加到數組末尾,並返回修改後的數組長度。pop()方法從數組末尾移除最後一項,減少數組的length值

var students = [];students.push("bluce","jordan","marlon","kobe");//入棧4項alert(students.length);   //4alert(students[0]);     //"bluce",第一項在棧的底部alert(students[1]);     //"jordan"students.push("paul");alert(students.length);   //5var item = students.pop(); //"paul"alert(students.length);   //4

2、Array的隊列方法

棧資料結構的訪問規則是LIFO(後進先出),而隊列資料結構的訪問規則是FIFO(First-In-First-Out,先進先出)。隊列在列表的末端添加項,從列表的前端移除項。push()方法是向數組末端添加項的方法,因此要類比隊列只需一個從數組前端取得項的方法——shift(),其能夠移除數組中的第一個項並返回該項,同時數組的length-1。結合使用shift()和push()方法,可以像使用隊列一樣使用數組。



var students = [];students.push("bluce","jordan","marlon","kobe");//入隊4項//students=["bluce","jordan","marlon","kobe"];alert(students.length);   //4alert(students[0]);     //"bluce",第一項在棧的底部alert(students[1]);     //"jordan"students.push("paul");alert(students.length);   //5//students=["bluce","jordan","marlon","kobe","paul"];var item = students.shift();  //"bluce"alert(students.length);   //4//students=["jordan","marlon","kobe","paul"];

此外,ECMAScript還提供了unshift()方法,它能在數組前端添加任意個項並返回新數組的長度。因此,結合使用unshift()和pop()方法,可以從相反的方向來類比隊列,即在數組的前端添加項,從數組末端移除項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.