What is an array?
Arrays are a fundamental part of most programming languages and scripting languages. Arrays are simply an ordered stack of data items with the same data type. Using arrays, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.For example, say you have three Frequently Asked Questions that you want to store and write to the screen. You could store these in a simple variable like this:
faqQuestion1 = "What is an array?"
faqQuestion2 = "How to create arrays in JavaScript?"
faqQuestion3 = "What are two dimensional arrays?"
Visualizing Arrays
Arrays can be visualized as a stack of elements.Array | |
0 | What are JavaScript arrays? |
1 | How to create arrays in JavaScript? |
2 | What are two dimensional arrays? |
Creating Arrays in JavaScript
Most languages use similar syntax to create arrays. JavaScript arrays are created by first assigning an array object to a variable name...var array_name = new Array(number_of_elements)
array_name[0] = "Array element"
So, using our prior example, we could write:
var faq = new Array(3)
faq[0] = "What are JavaScript arrays"
faq[1] = "How to create arrays in JavaScript?"
faq[2] = "What are two dimensional arrays?"
Accessing Arrays in JavaScript
You can access an array element by referring to the name of the array and the element's index number.Displaying Array Elements
document.write(faq[1])
Modifying the Contents of an Array
You can modify the contents of an array by specifying a value for a given index number:faq[1] = "How to modify an array?"
No comments:
Post a Comment