作业:实现一个堆栈类,具备 push、pop 功能
来源:2-17 Class

慕勒7675915
2019-11-21
老师,帮批改下吧
es6方式:
class Myarray {
constructor(arr) {
this.arr = arr;
}
myPop() {
if (this.arr.length === 0) return undefined;
return Number(this.arr.splice(this.arr.length - 1, 1))
}
myPush() {
let _this = this;
Array.from(arguments, el => _this.arr.splice(_this.arr.length, 0, el))
return this.arr.length;
}
}
let arr = Array.of(1, 5, 6, 7, 8)
let myArray = new Myarray(arr);
console.log(myArray.myPop(), arr)
console.log(myArray.myPush(null), arr)
直接挂载方式
Array.prototype.myPop = function () {
if (this.length === 0) return undefined;
return Number(this.splice(this.length - 1, 1))
}
Array.prototype.myPush = function () {
let _this = this;
Array.from(arguments, el => _this.splice(_this.length, 0, el))
return _this.length;
}
console.log(arr.myPop(), arr)
console.log(arr.myPush(0, 3, 4, 3, 2), arr)
写回答
1回答
-
快乐动起来呀
2019-11-21
优秀,看了下算是一个思路,可以想想有更好的方法吗
032019-11-30
相似问题
实际开发中应该怎么应用面向对象
回答 1
安装准备环境啥意义
回答 1