棧被稱為一種后進先出( LIFO, last-in-first-out) 的數據結構。
tips:pop()&peek()的區別:
pop() 方法可以訪問棧頂的元素, 調用后, 棧頂元素從棧中被永久性地刪除。
peek() 方法則只返回棧頂元素, 而不刪除它。
function Stack() { this.dataStore = []; this.top = 0;//top的值等同於數組內的元素個數 this.push = push; this.pop = pop; this.peek = peek; this.clear = clear; this.length = length; } function push(element) { this.dataStore[this.top++] = element; } function pop() { return this.dataStore[--this.top]; } function peek() { return this.dataStore[this.top - 1]; } function length() { return this.top; } function clear() { this.top = 0; } var s = new Stack(); s.push("David"); s.push("Raymond"); s.push("Bryan"); document.write("length: " + s.length() + "<br />"); //document.write("length: " + s.top + "<br />");//與上述結果相同 document.write(s.peek() + "<br />");//peek() 方法則只返回棧頂元素, 而不刪除它。 var popped = s.pop(); document.write("The popped element is: " + popped + "<br />"); s.clear(); document.write("length: " + s.length() + "<br />"); document.write(s.peek() + "<br />");