棧
棧是一種遵從後的進先出原則的有序集合
- push(val) 新增一個新元素到棧頂
- pop() 移除棧的元素,同時返回被移除的元素
- peek() 返回棧頂的元素,不對棧做任何修改
- isEmpty() 如果棧裡沒有任何元素就返回true,否則返回false
- clear() 移除棧裡的所有元素
- size() 返回棧裡的元素個數

目錄

inex.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src='./stack.js'></script>
<script src='./stack-es6.js'></script>
</head>
<body>
aa
</body>
</html>
複製程式碼
stack.js
var Stack = function(){
var items = [];
// this.items = [];
this.push= function(val){
items.push(val)
}
this.pop = function(){
return items.pop()
}
this.peek = function(){
return items[items.length-1]
}
this.isEmpty = function(){
return items.length === 0
}
this.clear = function(){
items = []
}
this.size= function(){
return items.length
}
}
var s1 = new Stack()
複製程式碼
var items = []
和this.items = []
的區別: this.items是公有的,s1,s2都能訪問得到
var s1 = new Stack()
var s2 = new Stack()
複製程式碼


stack-es6.js
class StackEs6{
constructor(){
this.items = []
}
push(val){
this.items.push(val)
}
pop(){
return this.items.pop()
}
size(){
return this.items.length
}
peek(){
return this.items[this.items.length-1]
}
isEmpty(){
return this.items.length === 0
}
clear(){
this.items = []
}
size(){
return this.items.length
}
}
var s2 = new StackEs6()
複製程式碼
2種實現對比


例項,10進位制轉2進位制
- 十進位制數是組成以10為基礎的數字系統,有0,1,2,3, 4, 5, 6, 7, 8, 9十個基本數字組成
- 二進位制數(binaries)是逢2進位的進位制,0、1是基本算符

var tenToTwo = function(number){
var s2 = new StackEs6()
var remainder //餘數
var str = '';
while(number >0){
remainder = number%2
number =Math.floor(number/2)
s2.push(remainder)
}
while(s2.isEmpty() === false){
str+= s2.pop()
}
return str
}
複製程式碼


棧的體現
function f1(){
return console.log('f1 finish')
}
function f2(){
f1()
return console.log('f2 finish')
}
複製程式碼

