I'm just playing with some JavaScript and have the following code:
function Stack() {
// Wrapper class for Array. This class only exposes the push
// and pop methods from the Array and the length property
// to mimic the a LIFO Stack.
// Instantiate new Array object.
this.stack = new Array();
// Pushes a new value on to the stack.
// @param arg to be pushed.
this.push = function(arg) {
return this.stack.push(arg);
}
// Pops a value from the stack and returns it.
this.pop = function() {
return this.stack.pop();
}
// Get size of the Stack.
this.size = function() {
return this.stack.length;
}
}
var stack = new Stack();
// Push 10 items on to the stack
for (var i = 0; i < 10; i++) {
stack.push(i);
}
for (var i = 0; i < stack.size(); i++) {
console.log(stack.pop());
}
The first part defines a Stack object that is really just a wrapper around the native Array object, but only exposes some methods and properties to make it like a LIFO stack. To test it I wrote the code at the bottom. However, when I try to use stack.size() to return the current size of the stack in the for loop the loop only iterates 5 times. Whereas if I assign the return value of that method call to a variable and pass the variable in to the for loop it iterates over the correct number of times (10). Why is this? Should I not be able to use stack.size() inside the for loop?