How to Factor for a Range of Numbers in JavaScript
- 1). Launch your HTML editor, open an HTML file and add the JavaScript code shown below to the document's script section:
var currentRange = {
2, 7, 13, 29, 87, 99
}
var newFactor = 3;
The currentRange object holds the values of your current range of numbers. Replace those values if you like with new ones. Replace 3 with the factor you wish to apply to the range. - 2). Paste the following code below the code listed in the previous step:
function factorRange(currentRange, newFactor)
{
var newRange = [];
var rangeCount =currentRange.length;
for (var i=0; i < rangeCount; i++)
{
newRange.push(currentRange[i] * newFactor)
}
return newRange;
}
alert(factorRange(currentRange, newFactor));
This function creates a new range object named newRange. The code loops through each element in the current range, multiplies it by your factor and adds each factored number to the newRange object. The last statement in the function returns that object to the calling function. The alert function allows you to test the factorRange function by passing it your set of test values. - 3). Save your HTML document and view it in a browser. The Web page loads and runs the JavaScript code which factors your range. The alert box opens and displays the new range.
- 4). Remove the alert function after testing this code. Note the currentRange variable on the first line of code. The square brackets around the numbers in the range create a JavaScript literal object. Literal objects are similar to arrays. When adding numbers to this object, separate them by commas. Do not place a comma after the last number in the range.
Source...