Frage

I am trying to create an array that begins at 0.05 and ends at 2.5. I want the values in between the min and max to grow by increments of 0.245.

var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];

the final output should be like this:

[0.05, 0.0745, 0.99, 0.1235, 0.148 ... 2.5]
War es hilfreich?

Lösung 2

do like

var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];


for(var i=min; i<max;i=i+increments) {
    arr.push(i);
}
arr.push(max);

console.log(arr);

Andere Tipps

using ES6/ES2015 spread operator you can do this way:

let min = 0.05,
    max = 2.5,
    items = 100,
    increments = ((max - min) / items);

let result = [...Array(items + 1)].map((x, y) => min + increments * y);

if you need to round your numbers to x number of digits you can do this way:

let result = [...Array(items + 1)].map((x, y) => +(min + increments * y).toFixed(4));

Here is an example of the code

Try this:

var min = 0.05;
    var max = 2.5;
    var increments = ((max - min) / 100);
    var arr = [];

    for (var i = min; i < max; i +=increments) {
        arr.push(i);
    }
    arr.push(max);

The basic idea is this:

for (var val=min; val<=max; val+=increments) {
  arr.push(val);
}

Keep in mind that floating point operations often have rounding errors. To fix them, you might want to round the value at each step:

var val = min;
while (val <= max) {
  arr.push(val);

  val += increments;
  val = Math.round(val*1000)/1000; // round with 3 decimals  
}

In some cases you may get wrong results due to rounding errors if you just increment number on each iteration. More correct way is:

var min = 0.05;
var max = 2.5;
var increments = (max - min) / 100;
var arr = [];
for (var i = 0; i <= 100; ++i)
    arr.push(min + increments * i);
function GetArray(minValue, maxValue, step) {
        var resArray = [];
        if (!isNaN(minValue) || !isNaN(maxValue) || !isNaN(step)) {
            for (var i = minValue; i <= maxValue; i=i+step)
            {
                resArray.push(i);
            }
        }
        return resArray;
    }

you can use this function

function test(){
   var min = 0.05;
   var max = 2.5;
    var increments = (max-min)/100;
    var arr = [];
    for(var min=0.05;min<=max;min=min+increments){
            arr.push(min);
    }
   alert(arr);
   }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top