JavaScript中数组的栈方法和队列方法

前端之家收集整理的这篇文章主要介绍了JavaScript中数组的栈方法和队列方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

JavaScript ECMAScript给数组提供了模拟其他数据结构的方法包括方法和队列方法
其中栈数据结构的访问规则是LIFO,也就是后进先出,提供了push()和pop()方法。push()接收任意数量参数,然后依次推入数组末尾,并修改数组长度。pop()移除末尾最后一项并返回该值,然后减少十足的长度。
而队列数据结构的访问规则则是FIFO,也就是后进后出,提供了shift()和unshift()方法。shift()方法把数组的第一个元素从其中删除,并返回第一个元素的值。而unshift()方法刚好相反,向数组的开头添加一个或更多元素,并返回新的长度。
但是一般把两者混合使用,来进行数据操作:
首先是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

首先是unshift()和pop():

var colors = new Array();                    //创建一个数组
var count = colors.unshift("red","green");  //推入两项
alert(count);                                //2
count = colors.unshift("black");             //推入另一项
alert(count);
var item = colors.pop();                     //取得最后一项
alert(item);                                 //"green"
alert(colors.length);                        //2
原文链接:https://www.f2er.com/js/416056.html

猜你在找的JavaScript相关文章