1. Computing

Maths Array Class

1. Introduction and Sample

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Obtain the Script

If you are working with several arrays of numbers then you may have a need to be able to change all of the values in one array based on the values in a second array. To make such calculations easier I have created a Javascript class called mathArray that includes methods that can perform a range of numerical manipulations on the number arrays for you using single commands.

We'll start by looking at what methods and properties I have created in the class and what they can do.

The first thing we need to be able to do is to define a mathArray. We do this using the following code which passes the values to be loaded into the array as a comma separated text string. Any non-numeric values in the string will be discarded as a mathArray can only contain numbers.

var vals = "1,2,3,4";
var mA1 = new mathArray(vals)

Now we can make use of the mathArray methods to perform calculations on all of the entries in the array in one command. To add each entry in a mathArray mA2 to the corresponding entries in mathArray mA1 we use:

mA1.add(mA2);

Similarly if we want to subtract each entry in a mathArray mA2 from the corresponding entries in mathArray mA1 we use:

mA1.subtract(mA2);

Multiplying all of the values in the mathArray by a set value is easy too:

var multiplier = 3;
mA1.multiply(multiplier);

Dividing is just as easy (and doesn't even need a separate method):

var divisor = 3;
mA1.multiply(1/divisor);

We can discard all of the values currently stored in the mathArray and replace them with new ones:

var vals = "5,6,7";
mA1.replace(vals)

We can also test if two mathArrays are equal (both having exactly the same numbers in the same positions within the array):

if (mA1.equal(mA2)) alert('equal');

To reduce all of the entries in a mathArray that are above a set maximum value to that maximum we can use:

var max = 255;
mA1.max(max);

Similarly to increase all of the values in the array below a set minimum value to that minimum we can use:

var min = 0;
mA1.min(min);

If you are working with integers then multiplying by a fraction may result in non-integers in the array. To change them back to integers use:

mA1.intg();

Finally, to actually access the values within a mathArray to use them after you have finished doing the calculations we use the mathArray.value property which contains the actual array of numbers. For example:

document.getElementById('patch').style.backgroundColor = 'rgb(' + mA1.value[0] + ',' + mA2.value[1] + ',' + mA3.value[2] + ')';

If you want to be able to use this class to simplify your numerical array calculations then all you need to do is to obtain the mathArray script and add it to your page.

Related Video
Zip File 101
Computer Cable Ports 101

©2013 About.com. All rights reserved.