# 手写栈
规则
- 先进后出
- 能拿栈的深度
- 能读取最顶层元素
- 判断空/清空
const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.top); // 2
console.log(stack.length); // 2
console.log(stack.pop()); // 2
console.log(stack.length); // 1
console.log(stack.isEmpty()); // false
stack.clear();
console.log(stack.isEmpty()); // true
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
class Stack {
stack = [];
push(item) {
this.stack.push(item);
}
pop(item) {
return this.stack.pop(item);
}
get top() {
return this.stack[this.stack.length -1];
}
get length() {
return this.stack.length;
}
clear() {
this.stack = [];
}
isEmpty() {
return this.stack.length === 0;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21