The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and the string should be enclosed between either “double quotes” or ‘single quotes’. You can get the structure of by using JSON.stringify() or not, here you will see the use of JSON.stringify(). For other procedure, you can check this link.
Syntax:
JSON.stringify(value, replacer, space)
The Functionality of the alert() is to first give information to the user before gets proceeding further. So, in the below code, the button on the click function(Alert()) has two alerts (alert()), after displaying all the alerts it gets further with the webpage. By clicking ‘ok’ in the alert box it displays the next alert until all are done.
Let’s check the type of alerts that can be applied:
- alert(JSON.stringify(guardians)): It displays as is array structure.
- alert(JSON.stringify(guardians, 9, 1)): It displays the customized structure, where the 9 acts as a replacer, makes array elements get printed in vertically, and 1 acts as a space number and provides one space between elements.
- alert(JSON.stringify(guardians, “”, 5)): It displays, the customized structure, where the “” acts as a replacer, makes array elements get printed vertically, and 5 acts as a space number and provides five spaces between elements.
Example 1:
HTML
< h1 style = "color:Green;" > neveropen </ h1 > < h3 > Getting array structure JSON.stringify </ h3 > < p id = "d1" ></ p > < input type = "button" onclick = "Alert()" value = "Click Here" /> < script > function Alert() { // Array structure var guardians = ["Quill", "Gamora", "Groot", "Rocket", "Drax", 21]; // Prints the array elements with a comma // separated but not the structure document.getElementById("d1").innerHTML = "Guardians = " + guardians; // Alerts the window with the array alert(JSON.stringify(guardians)) // Alerts the window with a customized array alert(JSON.stringify(guardians, 9, 1)) } </ script > |
Output:
Example 2: You can also get the structure of an Associate array easily.
html
<!DOCTYPE html> < html > < head > < title > How to view array of a structure in JavaScript? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:Green;" > neveropen </ h1 > < h3 > Getting associate array structure JSON.stringify </ h3 > < p id = "d1" ></ p > < input type = "button" onclick = "Alert()" value = "Click Here" /> < script > function Alert() { // Array structure var guardians = { "Newton": "Gravity", "Albert": "Energy", "Edison": "Bulb", "Tesla": "AC" }; // Alerts the window with the array alert(JSON.stringify(guardians)) // Alerts the window with a // customized array alert(JSON.stringify(guardians, 9, 1)) // Alerts the window with a // customized array alert(JSON.stringify(guardians,"",5)) } </ script > </ body > </ html > |
Output: