home
clear breadcrumbs
search
login
 
multi_dimensional_array
http://www.dyn-web.com/javascript/arrays/|Great site on arrays , , , ====== JavaScript Multidimensional Arrays ====== , , , A JavaScript multidimensional array is an array of arrays, or, in other words, an array whose elements consist of arrays. We demonstrate with the following multidimensional array: , , var ar = , apple, orange, pear, , carrots, beans, peas, , cookies, cake, muffins, pie , ; , ====== How to Access Elements of a Multidimensional Array ====== , , , To access elements of the nested arrays, use square brackets as the following demonstrates: , , alert( ar21 ); // cake , The first square bracket references the desired element in the outer array. The second square bracket references the desired element in the inner array. So ar21 references the second element in the third sub-array. (JavaScript array indexes start at zero.) , , ====== Adding and Removing Elements in Multidimensional Arrays ====== , , , You can use square bracket notation to add elements to the inner arrays. The following demonstrates adding a new element at the end of the first sub-array, with console.log used to display the result: , , ar03 = banana; , console.log( ar0 ); // DQappleDQ, DQorangeDQ, DQpearDQ, DQbananaDQ , You can apply array methods to the nested arrays. Here we use the push method to add two new elements to the second sub-array: , , ar1.push(kale, broccoli); , console.log( ar1 ); // DQcarrotsDQ, DQbeansDQ, DQpeasDQ, DQkaleDQ, DQbroccoliDQ , Here we demonstrate using the push method to add a new array element to the outer array: , , ar.push( fried chicken, pot roast, rib-eye steak ); , You can also use array methods to remove elements from sub-arrays, as we demonstrate here with the pop method: , , ar2.pop(); // remove last element from 3rd sub-array , alert( ar2 ); // cookies,cake,muffins , Find out more about methods to add and remove array elements. , , ====== Looping through Multidimensional Arrays ====== , , , When you want to iterate over the elements of a multidimensional array, use nested for loops: , , // outer loop applies to outer array , for (var i=0, len=ar.length; i