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?
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 slice
call.
// The same as stack[stack.length-1], just slower and NOT idiomatic var top = stack.slice(-1)[0];
To extract an element there is however pop
:
// Add two top-most elements of the stack var a = stack.pop(); var b = stack.pop(); stack.push(a + b);
var stack = []; stack.push("id1"); stack.push("id2"); console.log(stack[stack.length-1]); // the top element console.log(stack.length); //size
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With