如何从堆栈中获取第一个元素 这是我的代码
var stack = [];
stack.push(id1);
stack.push(id2);
我知道java中有类似peek的东西。 JS中有没有类似的方法可以获取最上面的元素?
最佳答案
不幸的是,要检查最上面的元素,您必须显式索引它
var top = stack[stack.length-1];
语法stack[-1]
(在Python中适用)不起作用:负索引仅作为slice
调用的参数有效。
// The same as stack[stack.length-1], just slower and NOT idiomatic
var top = stack.slice(-1)[0];
要提取元素,需要pop
:
// Add two top-most elements of the stack
var a = stack.pop();
var b = stack.pop();
stack.push(a + b);
关于javascript - 使用javascript在堆栈中进行查看操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42501871/