Home About Me

Using JavaScript Arrays to Stand In for Simple Local Data Storage

A small office tool was needed for everyday work. The first idea was to build it with VBA, but that was unfamiliar territory. C was more familiar, yet a command-line program would have been awkward for the person actually using it.

So the practical option became a web-based tool. PHP would normally have been the easy choice, except the work environment could not rely on external network access. In the end, JavaScript was the most workable route, learned and applied on the fly.

Because a database was not available, the data had to be stored directly in memory. That made arrays especially useful, including nested arrays to simulate two-dimensional and three-dimensional structures.

Defining and assigning a basic array

A simple one-dimensional array can hold values of different types:

    var jz = newArry();
    jz[0] = 10;
    jz[1] = "hello";
    jz[2] = 23.4;

This array contains three values:

  • 10 as an integer
  • hello as a string
  • 23.4 as a floating-point number

They can be read like this:

    alert("jz[0] is "+jz[0]+"\n jz[1] is "+jz[1]+"\n jz[2] is "+jz[2]);

Building a two-dimensional array

A two-dimensional array can be formed by assigning an array to each element of a one-dimensional array.

Example:

    var jz = newArry();
    jz[0] = newArry(1,2);
    jz[1] = newArry(3,4);
    jz[2] = newArry(5,6);

Values can then be accessed with expressions such as jz[0][0], jz[0][1], and jz[0][2].

A simple three-dimensional array example

When one more layer of nesting is added, the array can be used to hold more structured data:

    var jz newArry();
    jz[0] = newArry([100,200],[300,400],[500,600])
    jz[1] = newArry(['str1','str2'],['str3','str4'],['str5','str6']);
    jz[2] = newArry([2.24,3.2],[12.9,89.01],[38.04,7.6]);

An element inside this three-dimensional structure can be accessed with syntax like jz[0][1][0].

For cases where no database can be used, this kind of nested array setup is a straightforward way to keep small amounts of structured data inside a JavaScript-based tool.