- Getting Started
- Variables and Types
- Manipulating Arrays
- Function Context
Pushing and popping
Arrays can also function as a stack. The
pop methods insert and remove variables from end end of an array.
For example, let's create an empty array and push a few variables.
var myStack = ; myStack.push(1); myStack.push(2); myStack.push(3); print(myStack);
This will print out:
After pushing variables to the array, we can then pop variables out from the end.
This will print out the variable we popped from the array, and what's left of the array:
3 // the result from myStack.pop() 1,2 // what myStack contains now
Queues using shifting and unshifting
unshift methods are similar to
pop, only they work from the beginning of the array. We can use the
shift methods consecutively to utilize an array as a queue. For example:
var myQueue = ; myQueue.push(1); myQueue.push(2); myQueue.push(3); print(myQueue.shift()); print(myQueue.shift()); print(myQueue.shift());
shift keyword will remove the variables of the array in the exact order they were inserted in, and the output will be:
1 2 3
unshift method is used to insert a variable from the beginning of an array. For example:
var myArray = [1,2,3]; myArray.unshift(0); print(myArray); // will print out 0,1,2,3
var myArray = [0,1,2,3,4,5,6,7,8,9]; var splice = myArray.splice(3,5); print(splice); // will print out 3,4,5,6,7 print(myArray); // will print out 0,1,2,8,9
After splicing the array, it will only contain the part before and after the splicing. The splice is equal to all the variables between 3 and 7 (including), and the remainder of the array, which contains all variables between 0 and 2 (including), and 8 to 9 (including).