Javascript (back to basics) arrays?
Can someone please help me. I have been writing javascript and jquery for over a year now, but there is one topic I have never run across. ARRAYS. can someone give me a basic idea on how arrays in javascript work and how I can use them. I am trying to store an array of arrays that contain strings. Like this
- Base Array
- [0] Sub Array
- [0] 'Hello World'
- [1] 'Hey What's Up World'
- [1] Sub Array
- [0] 'Hello America'
- [1] 'Hello UK'
- [0] Sub Array
And I might also have so开发者_开发问答me numeric values in there too. So, how can I go about this task.
var array = [
['Hello World', "Hey What's Up World"],
['Hello America', 'Hello UK'],
[1, 2, 3]
];
array[0][1]; // "Hey What's Up World"
array[2][2]; // 3
Like this:
var array = [
[ 'Hello World', 'Hey What Up World' ],
[ 'Hello America', 'Hello UK' ]
];
keep in mind that Arrays in javascript can be both numeric and hash, as in...
var foo = new Array();
foo[0] = "a";
foo[1] = "b";
etc...
or
foo["key1"] = "a";
foo["key2"] = "b";
The primary difference here is that if you use it in the hash context, you can't get a length (array.length) as it will always be 0. However, if you want to loop through your hash you can do it like this:
for(myKey in foo){
...
}
where mykey will take on the key and you can get the value by using foo[mykey], in the above loop.
You can also loop this way through a numeric array, in which case myKey will just run through all the numbers.
Lastly, if you arbitrarily stick something into a high numbered element as in...
foo = new Array();
foo[1000] = "what happened to the first 999";
0 - 999 will all be initialized to null, but the length of this array will now immediately be 1001;
As to adding multiple dimensions, since every item in the array is just an Object, it can hold whatever you want it to, including another Array.
Hope that helps.
精彩评论