本文實例講述了JS棧stack類的實現與使用方法。分享給大家供大家參考,具體如下:
棧是一種“先進后出”的數據結構,原理如下圖所示:
示例代碼:
/*使用棧stack類的實現*/function stack() { this.dataStore = [];//保存棧內元素,初始化為一個空數組 this.top = 0;//棧頂位置,初始化為0 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 clear(){ this.top = 0;}function length(){ return this.top;}/*測試stack類的實現*/var s = new stack();s.push("aa");s.push("bb");s.push("cc");console.log(s.length());//3console.log(s.peek());//ccvar popped = s.pop();console.log(popped);//ccconsole.log(s.peek());//bb
這里使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.VeVB.COm/code/HtmlJsRun測試上述代碼,可得如下運行結果:
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript數據結構與算法技巧總結》、《JavaScript數學運算用法總結》、《JavaScript排序算法總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript查找算法技巧總結》及《JavaScript錯誤與調試技巧總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答