myArray[0] = "yellow balloon";
myArray[1] = "red balloon";
myArray[2] = "blue balloon";
myArray[3] = "pink balloon";
In this example, the element with the index number of 0 has a value of "yellow balloon". The element with an index number 3 has a value of "pink balloon". Just as with any variable, you can give an array any name that complies with the rules of naming JavaScript variables. By assigning index numbers in arrays, JavaScript gives you the ability to make a single variable name hold a nearly unlimited list of values.
Just so you don't get too carried away, there actually is a limit to the number of elements that you can have in an array, although you're very unlikely to ever reach it. The limit is 4,294,967,295 elements.
In addition to naming requirements (which are the same for any type of variable), arrays have a couple of other rules and special properties that you need to be familiar with:
- Arrays are zero-indexed
- Arrays can store any type of data
Arrays are zero indexed
The first element in a JavaScript array always has an index number of 0What this means for you is that myArray[3] is actually the fourth element in the array.
Zero-based numbering is a frequent cause of bugs and confusion for those new to programming, but once you get used to it, it will become quite natural. You may even discover that there are benefits to it, such as the ability to turn your guitar amp up to the 11th level.
Arrays can store any type of data
Each element in an array can store any of the data types, as well as other arrays. Array elements can also contain functions and JavaScript objects.While you can store any type of data in an array, you can also store elements that contain different types of data, together, within one array, as shown below.
Storing Different Types of Data in an Array
item[0] = "apple";
item[1] = 4+8;
item[2] = 3;
item[3] = item[2] * item[1];
No comments:
Post a Comment