// 创建一个构造函数
function Stack() {
// 对象里的数值为空
this.items = []
// 数据进入栈
Stack.prototype.push = function (value) {
return this.items.push(value)
}
// 数据从栈取出
Stack.prototype.pop = function () {
return this.items.pop()
}
// 查看栈顶的元素 索引 -1
Stack.prototype.peek = function () {
return this.items[this.items.length - 1]
}
// 判断栈是否为空
Stack.prototype.empty = function () {
return this.items === 0
}
// 获取栈的大小
Stack.prototype.size = function (value) {
return this.items.length
}
// 栈中的元素转换成字符串
Stack.prototype.toString = function () {
var string = ''
for (let i = 0; i < this.items.length; i++) {
string += this.items[i] + ','
}
return string = string.substring(0, string.length - 1)
}
}
// 实例化对象
let s = new Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(5)
console.log(`将元素${s}压入栈`);
s.pop()
s.pop()
console.log(`取出了二个元素,还剩元素${s}在栈里`);
var a = s.peek()
console.log(`栈顶元素是${a}`);
var b = s.empty()
if (b === false) {
console.log('栈不是空的')
} else {
console.log('栈是空的');
}
var c = s.size()
console.log(`栈里有${c}个元素`);
var d = s.toString()
console.log(`栈中元素用字符串表示为:${d}`);