ECMAScript數(shù)組也提供了一種讓數(shù)組的行為類似于其他數(shù)據(jù)結(jié)構(gòu)的方法。具體說來,數(shù)組可以表現(xiàn)的就像棧一樣,后者是可以限制插入和刪除項(xiàng)的數(shù)據(jù)結(jié)構(gòu)。棧是一種LIFO(Last-In-First-Out,后進(jìn)先出)的數(shù)據(jù)結(jié)構(gòu),也就是最新添加的項(xiàng)最早被移除,。而棧中項(xiàng)的插入(叫做推入)和移除(叫做彈出),只發(fā)生在一個(gè)位置—-棧的頂部。js為數(shù)組專門提供了push()與pop()的方法,以便實(shí)現(xiàn)類似棧的行為。
push()方法可以接受任意數(shù)量的參數(shù),把它們逐個(gè)添加到數(shù)組末尾,并返回修改后數(shù)組的長度。而pop()方法則從數(shù)組末尾移除最后一項(xiàng),減少數(shù)組的length值,然后返回移除的項(xiàng)。
<scriPPT> var colors =new Array(); var count =colors.push("red","green"); //推入兩項(xiàng) alert(count) //2 count = colors.push("black");//推入另一項(xiàng) alert(count);//3 var item = colors.pop();//取得最后一項(xiàng) alert(item); //"black" alert(colors.length);//2</script>除了上面的方法之外,還可以將棧方法與其他的數(shù)組方法連用:
<script> var colors =new Array(); var count = colors.unghift("red","green");//推入兩項(xiàng) alert(count); //2 count=colors.unghift("black");//推入另一項(xiàng) alert(count);//3 var item = colors.pop();//取得最后一項(xiàng) alert(item);//"green" alert(colors.length); //2</script>這個(gè)例子創(chuàng)建了一個(gè)數(shù)組并使用unghift()方法先后推入了三個(gè)值。首先是“red”和”green”,然后是”black”,數(shù)組中各項(xiàng)的順序?yàn)椤眀lack”,”red”,”green”.在調(diào)用pop()方法時(shí),移除并返回的是最后一項(xiàng)。即”green”.
注意:IE7及更早版本對javaScript的實(shí)現(xiàn)中存在一個(gè)偏差,其unghift()方法總是返回unghift而不是數(shù)組的新長度。IE8在非兼容模式下會返回正確的長度值。
新聞熱點(diǎn)
疑難解答