Here are some useful advantages of using arrays:
DECLARE YOUR ARRAY
<arrayname> = new Array(<# of elements>);
myArray = new Array(50);
*Just make sure that you capitalize the "A" in array on the right hand side of the equals sign. If not, you will get an error.
Now just to sort of discuss why arrays are important and useful. What if you needed to get the average of say, 50 numbers? Without an array, you would write 50+ lines of code. On the other hand, with an array you can accomplish this by 7 or 8 lines of code. And that would be the same if you needed to find the average of 100000 numbers. Instead of writing 100000 lines of code, 7 or 8 will do the trick.
Example of using an array to average numbers:
*In the code sample we used a for loop. We will discuss these a bit later.
Joining Array Elements
Ok, what if you had an array and you wanted to combine each element to form a single sentence? Well, with the join(); function, it is quite simple! The join function will convert your array elements to a string. And a comma (,) is inserted between each element as it is converted. However, you can specify a different separator.
This would output: How are you this morning?
Notice my join function. it has ' ' included. This makes it output a space between each element. Also doing just, .join(" "); would work. But if nothing was inside the ( and ), it would output: How,are,you,this,morning? It defaults with the comma. If you want anything different, you must specify it. Just make sure you surround it with ' and ' because just .join( ) would make an error.
Sorting Array Elements
If sort(); is used on numbers, the numbers are sorted alphabetically instead of numerically. So say an array with: 1,2,3,4,11,22 would sort as: 1, 11, 2, 22, 3, 4. So basically sort(); has to be used with strings.
Here is an example of an array and the sort(); property:
This would output: apples,banannas,mangos,oranges,pears
Just as the .join(); function, you can enter html between the ( and ). So, if you put, .sort('<br>'); this would output each item on a line by itself. And using .sort(" "); would put a space between each item instead of a comma.
No Comments for this page.