This JavaScript program demonstrates various methods for allocating arrays and entries within arrays.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> </head> <body> <script type="text/javascript" src="ArrayAllocations.js"></script> </body> </html>
// Create an empty array with no elements in it. var iaA = []; // Allocate new entries by assigning them values. iaA[0] = 4; iaA[1] = 5; // Skipped elements are undefined, but are in the array. iaA[3] = 14; for(var i = 0; i < iaA.length; ++i) { document.writeln("iaA["+ i + "] = " + iaA[i] + "<br />"); } document.writeln("<br />"); // A simple array initializtion. This array can be extended var iaB = [40,19,301]; // Add an element to the end of the array iaB[iaB.length] = 65; // Add another element via a push iaB.push(81); for(var i = 0; i < iaB.length; ++i) { document.writeln("iaB["+ i + "] = " + iaB[i] + "<br />"); } document.writeln("<br />"); // An object that works like an associative array, but can not be indexed. var saAssoc = []; saAssoc["Simon"] = "Peter"; saAssoc["Saul"] = "Paul"; for (sName in saAssoc) { document.writeln("saAssoc["+ sName + "] = " + saAssoc[sName] + "<br />"); } document.writeln("saAssoc["+ 0 + "] = " + saAssoc[0] + "<br />"); document.writeln("<br />"); // Use the built-in Array constructor to allocate an empty array. var iaC = new Array(); // Allocate the entries of the array by pushing them iaC.push(11); iaC.push(22); iaC.push(33); for(var i = 0; i < iaC.length; ++i) { document.writeln("iaC["+ i + "] = " + iaC[i] + "<br />"); } document.writeln("<br />"); // Use the built-in Array constructor with a set of entries. var iaD = new Array(9,6,3,7); for(var i = 0; i < iaD.length; ++i) { document.writeln("iaD["+ i + "] = " + iaD[i] + "<br />"); } document.writeln("<br />"); // Use the built-in Array constructor to allocate an Array of undefined entries. // Note: This does not create an array with a single entry. var iaE = new Array(5); // Fill in the array as you see fit. iaE[2] = 800; for(var i = 0; i < iaE.length; ++i) { document.writeln("iaE["+ i + "] = " + iaE[i] + "<br />"); } document.writeln("<br />");
© 20072024 XoaX.net LLC. All rights reserved.