因此,我创建了一个函数,通过使用内置的 .push(e)
函数将用户输入的字符串推送到堆栈,如下所示:
push() {
const arrays = this.array.push(String(this.userInput))
console.log(this.array)
}
每次点击按钮,控制台都会更新数组,将用户输入的任何内容推送到我也制作的 HTML 文本字段中。我向 friend 展示了它,他们告诉我,这种方法有点作弊,因为我正在制作一堆堆栈,并且有一种方法可以...
Implement a Stack using only an index, a count, and an array.
从概念上讲,我知道它们是什么,索引是给定数组中的对象位置,数组是相同变量类型的对象的集合,计数表面上是计数(如果我错了,请纠正我? )。然而,作为计算机科学第一学期的学生,将这些概念结合在一起来实现堆栈有点超出了我的能力,有没有一种通俗易懂的方式来解释如何将这些东西结合在一起来实现堆栈?
最佳答案
要在不使用内置 push
方法的情况下执行您正在执行的操作,只需分配给数组当前长度处的索引即可。无需跟踪任何其他变量:
push() {
this.array[this.array.length] = String(this.userInput);
// if you also need your implementation to return the new length, then:
return this.array.length;
}
或者,对于pop
:
pop() {
const item = this.array[this.array.length - 1];
this.array.length = Math.max(this.array.length - 1, 0);
return item;
}
请记住,push
返回数组的新长度,因此 const arrays = this.array.push(String(this.userInput))
不会给你一个数组作为返回。
关于javascript - 使用数组、计数和索引实现堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524781/