JavaScript实现栈结构es6

本文介绍了一个使用JavaScript实现的基本栈结构。栈是一种后进先出(LIFO)的数据结构,主要功能包括进栈、出栈、查询是否为空、查询栈顶元素、获取栈的长度以及转换为字符串表示。通过具体实例展示了栈的操作过程。

 实现基本的栈结构,代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>栈</title>
	</head>
	<body>
		<script type="text/javascript">
			function Stack() {
				this.item = []
				//进栈
				Stack.prototype.push = data => this.item.push(data)
				//出栈
				Stack.prototype.pop = () => this.item.pop()
				//查询是否为空
				Stack.prototype.isEmpty = () =>  this.item.length === 0
				//查询第一个
				Stack.prototype.peek = () => this.item[this.item.length -1]
				//查询长度
				Stack.prototype.size = () => this.item.length
				//toString方法
				Stack.prototype.toString = () => {
					let res = ''
					for( let i in this.item) {
						res += this.item[i] + ' '
					}
					return res
				}
			}
			let s = new Stack()
			s.push(123)
			s.push(456)
			s.push(789)
			s.push(321)
			s.push(6547)
			s.push(987)
			s.push(0)
			console.log(s)
			s.pop()
			s.pop()
			console.log(s)
			console.log(s.peek())
			console.log(s.isEmpty())
			console.log(s.size())
			console.log(s.toString())
		</script>
	</body>
</html>

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值