In this blog, we will see how to create an array and its associated functions like push(), pop(). We will also create our own functions which can delete and insert elements at a given index eg: delete(3) deletes the element with index 3.
Tech stacks used:
Creating an array datatype
Everything in java exists as objects. This can be confirmed by looking at the below image, here you can see that everything is stored as key-value pair.
Step 1: We are using a constructor functions to create an object
For understanding better , try replacing the word “this” with “our” while reading. So you can see at line 19 : length of the object “our”= the number of arguments passed. Using the for loop we are assigning “our”= “x”, “our”= “y”, etc.
To change the appearance of output to match an array, we print the values stored in the object using:
The length is also taken into account when counting the total length of array. To rectify this problem, we will make the length attribute non enumerable( not countable).
Functions that can modify our array
To add functions to alter our array according to our needs, we use something called “prototype”. If you have a look at all the images added above you can see Prototype as array, object, etc.
Think of it this way, we have a basic idea of what a bike is, all the parts all its functions. Now every company designs and adds their own ideas to make different bikes we have today in market. Similarly to the array, we are adding pop() to modify the array by deleting its last element.
Now we will create a function पॉप (pop written in Hindi). This function when called, deletes the last element of the array.
I am sure you guys will be able to create your own functions to modify your array as per requirements. I will be posting more coding hacks weekly, so stay tuned.
Till then happy coding.