Array object is used to store multiple values in a single variable. In JavaScript, am array can hold different data types in a single array slot. An array can be constructed in the following ways:
- Using the array constructor.
- Using the array literal notation.
Using the array constructor:
An empty array is constructed in case when you do not know the exact number of elements to be inserted in the array.
Syntax:
- varmyArray=new array();
- varmyArray=new array(size);
Using Literal notion:
Array literal notations are comma-separated list of items enclosed by square brackets.
Syntax:
- varmyArray=[“element 1”,”element 2”];
- varmyArray=[6,true,false,true];
Demo: - Create a document called ArrayFunctions.html.
- Write the following code:
- <!DOCTYPE HTML>
-
- <HEAD>
- <TITLE>Array Functions</TITLE>
- </HEAD>
-
- <BODY>
- <SCRIPT type="text/javascript">
- myarray1 = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday");
- myarray2 = new Array(1, 2, 3, 4, 5);
- document.write("Array 1: " + myarray1 + "<br>");
- document.write("Array 2: " + myarray2 + "<br>");
- document.write("Concatenated arrays: " + myarray1.concat(myarray2) + "<br>");
- document.write("Joined two arrays: " + myarray1.join(myarray2) + "<br>");
- document.write("Array 1 pop out: " + myarray1.pop() + "<br>");
- document.write("Reversed array 1: " + myarray1.reverse() + "<br>");
- document.write("Shifted array 1: " + myarray1.shift() + "<br>");
- document.write("Sorted array 1: " + myarray1.sort() + "<br>");
- document.write("Array 2 in string format: " + myarray2.toString() + "<br>");
- </SCRIPT>
- </BODY>
-
- </HTML>
- Execute the script by Opening the file in the Web Browser. If you are using Internet Explore click on “Allow Blocked Content” to allow the script to execute and you are using Mozilla Firefox then click on allow “ActiveX Controls”.
Thank you for reading this article. If you need any help feel free to contact me.