var objStack = [] objStack.push(2); objStack.push(5);
objStack.push(8);
So here objStack will behave as a Stack object & it will follow FIFO (First-In First-Out) concept.
We can access the value of the object by –
objStack[1]; // It will give the 2nd element’s value, i.e 5. objStack.toString(); // It will give the values separated by comma, i.e 2,5,8. objStack.pop(); // It will retrieve last inserted value, i.e 8. But that element (8) will be removed from the stack object. se of QUEUE [push() & shift()]
Similarly Array class can be used a Queue by using push() & shift() method.
var objQueue = []; objQueue.push(4); objQueue.push(8);
objQueue.push(12);
objQueue.shift(); // It will give the first inserted value, i.e 4. But that element (4) will be removed from the queue object. Use of join() & split()
You can use join() methos to join the elements of the array & split() to do the reverse.
var arr = [1, 2, 3]; var outputStr = arr.join(‘ | ‘);
document.write(outputStr); // 1 | 2 | 3.
var str = ‘1 | 2 | 3’; var objString = str.split(‘ | ‘); for (var counter = 0; counter < splitObj.length; counter++) { document.write(objectString[counter]); } output: // 1, 2 ,3. Use of sort()
Javascript provide sort() method for sorting elements of an Array. But by default the method sorts the elements in alphabetical order. So, non-string elements are converted into strings before sorting operation, then sorting operation is done. Which results unexpected outcome while dealing with number.
e.g : – var arr = [9, 5, 10, 1]; arr.sort();
document.write(arr.toString());
The output will be “1, 10, 5, 9” which is wrong. So to avoid these kind of thing we can use a function for comparing the number and use it while sorting. That means we can write something like this –
// This function will return 0 if two numbers are equal else it will return either positive or negative number. function compareNum(num1, num2) { return num1 – num2;
}
We can use the user-defined compareNum() method while sorting numric array elements.
var arr = [9, 5, 10, 1]; arr.sort(compareNum); // We are passing the user-defined function name as parameter to the sort function.
document.write(arr.toString());
Now it will give the output as “1, 5, 9, 10”.