Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

peek operation in stack using javascript

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?

like image 766
JustCurious Avatar asked Feb 28 '17 06:02

JustCurious


2 Answers

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); 
like image 86
6502 Avatar answered Sep 21 '22 02:09

6502


var stack = [];  stack.push("id1");  stack.push("id2");  console.log(stack[stack.length-1]); // the top element  console.log(stack.length); //size
like image 38
Sagar V Avatar answered Sep 22 '22 02:09

Sagar V