js模擬棧和隊列

棧和隊列前端


棧:LIFO(先進後出)一種數據結構數組

隊列:LILO(先進先出)一種數據結構數據結構

使用的js方法code


1.push();能夠接收任意數量的參數,把它們逐個推動隊尾(數組末尾),並返回修改後的數組長度。隊列

2.pop();從數組末尾移除最後一項,減小數組的值,返回移除的項。ip

3.shift();移除數組第一項並返回該項同時將數組的長度減一。it

簡單實現棧方法


使用push()和pop()結合實現簡單棧數據

var colors = new Array();
var count = colors.push('red','white','blue');
alert(count);//3

var item = colors.pop();
alert(item);//blue
alert(colors.length());//2

簡單實現隊列兼容


使用shift()與push()結合實現簡單隊列

var colors = new Array();
var count = colors.push('red','green');
alert(count);//2

var item = colors.shift();
alert(item);//red
alert(colors.length());//1

額外補充


unshift()與shift()用途相反,unshift()在數組前端添加任意個項,並返回新數組的長度。

注意:IE7以及更早版本對JavaScript的實現中存在誤差,其unshift()方法老是返回undefined而不是新數組的長度。IE8在非兼容模式下會返回正確的長度值。

相關文章
相關標籤/搜索