使用 javascript 在堆栈中查看操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42501871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:12:16  来源:igfitidea点击:

peek operation in stack using javascript

javascriptstack

提问by JustCurious

How can I get the first element from my stack here is my code

我如何从我的堆栈中获取第一个元素,这是我的代码

var stack = [];
stack.push(id1);
stack.push(id2);

I know there is something like peek in java. Is there any similar method in JS using which i can get the topmost element?

我知道在 Java 中有类似 peek 的东西。JS 中有没有类似的方法可以使用它来获取最顶层的元素?

回答by 6502

To check the topmost element unfortunately you must explicitly index it

不幸的是,要检查最顶层的元素,您必须明确索引它

var top = stack[stack.length-1];

the syntax stack[-1](that would work in Python) doesn't work: negative indexes are valid only as parameters to slicecall.

语法stack[-1](在 Python 中有效)不起作用:负索引仅作为要slice调用的参数有效。

// The same as stack[stack.length-1], just slower and NOT idiomatic
var top = stack.slice(-1)[0];

To extractan element there is however pop:

然而,要提取一个元素pop

// Add two top-most elements of the stack
var a = stack.pop();
var b = stack.pop();
stack.push(a + b);

回答by Sagar V

var stack = [];
stack.push("id1");
stack.push("id2");
console.log(stack[stack.length-1]); // the top element
console.log(stack.length); //size

回答by pery mimon

If you just need one edge of your stack (head or tail is not matter) use it reversed:

如果您只需要堆栈的一个边缘(头或尾无关紧要),请将其颠倒使用:

I mean :

我的意思是 :

peek()become array[0],
unshift(v)become push()
shift()become pop()

peek()成为array[0]
unshift(v)成为push()
shift()成为pop()

some code:

一些代码:

class Stack{
  constructor(... args ){
    this.store = [... args.reverse()];
  }
  peek(){
    return this.store[0];
  }
  push(value){
    return this.store.unshift(value);
  }
  pop(){
   return this.store.shift();
  }
}

const stack = new Stack(1,2,3);
stack.push(4);
console.log(stack.peek());
stack.pop();
console.log(stack.peek())

or shorter

或更短

function Stack(...rest){
  var store = [... rest.reverse() ];
  return {
    push:(v)=> store.unshift(v) ,
    pop : _ => store.shift(),
    peek: _ => store[0]
    }
  }
  
var stack = Stack(1,2,3);
console.log(stack.peek());
stack.push(4);
console.log(stack.peek());
stack.pop(), stack.pop();
console.log(stack.peek());

回答by Abhilash A S

        var stack = [];
        stack.push("id1");
        stack.push("id2");
        var topObj = stack[0]
       console.log(topObj)