Maths Array Class
1. Introduction and Sample
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:
Similarly if we want to subtract each entry in a mathArray mA2 from the corresponding entries in mathArray mA1 we use:
Multiplying all of the values in the mathArray by a set value is easy too:
var multiplier = 3;
Dividing is just as easy (and doesn't even need a separate method):
var divisor = 3;
We can discard all of the values currently stored in the mathArray and replace them with new ones:
var vals = "5,6,7";
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;
Similarly to increase all of the values in the array below a set minimum value to that minimum we can use:
var min = 0;
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:
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 + ',' + mA2.value + ',' + mA3.value + ')';
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.