Let say you have an the following array:
var numbers = [3,4];
If you output the array in the browser console you will see that the array has two elements with the number 3 occupying index 0 and the number 4 occupying index 1.
Now let's use the push method to add a number 5 to the end of the array with the following code
numbers.push(5);
If output the array in the console you will see that there are 3 elements now with 5 being the last element in the array.
The next thing we want to do is add an element in the beginning of the array with the unshift() method. Let's add a number 2 as the first element of the array with the following code numbers.unshift(2);
If you output the array in the browser console you will see that now we have four elements not with the values 2,3,4,5
To get rid of the first element in the array you simply call the shift() method like the following code to get right the number 2 in the numbers array:
numbers.shift();
The opposite of shift() is the pop() method, the pop() method will remove the last element in the array.
numbers.pop(); will leave you with two elements in the array 3,4
The last thing we are going to look at is the delete keyword. With delete keyword we can delete an element based on the index of the array. For example we can delete the 3 in the array by specifying the index of the element, like the following code
delete numbers[0];
If you output the array in the browser console now you get have only one element remaining which is the element with the value 4.
There's something interesting when using the delete keyword. Even though we deleted the number 3 successfully. The length of the array is still 2, meaning there's an empty element occupying the first element of the array. So when you using the delete keyword there's some residual side effects that you would normally think about. It's almost like a soft delete.
Not bad this is surely nice way to add and remove in simple and easy method.
ReplyDelete