Ali-Alrabi
Ali-Alrabi

Reputation: 1698

I have javascript function that add numbers to array

I have javascript function that add numbers to array start form min to max and increase by step but when I use getNumbers(2, 20, 2); it print 2,22,222,2222,.... It doesn't increase can anyone help me please.

        function getNumbers(min, max, step) {
               var i;
              for(i=min ; i<max ; i+=step){
               array.push(i);
               alert(array);
            }

Upvotes: 2

Views: 101

Answers (3)

Flati
Flati

Reputation: 198

I see no problem with the function. Other than the array is not defined.

You're probably sending the variables in as a string, which causes concatenation instead of addition.

function getNumbers(min, max, step) {
    var array = [];
    for(var i = min ; i <= max ; i += step){
        array.push(i);
    }
    return array;
}

You might also need to make sure that you use i <= max in your loop, if you want to include the max.

Upvotes: 0

Abdul Jabbar
Abdul Jabbar

Reputation: 2573

Nothing wrong with your function, you must pass numbers, if the passing parameters are string, change them to numbers as i did below:

var array = new Array();
function getNumbers (min, max, step) {
              var i;
              for(i=min ; i<max ; i+=step){
               array.push(i);
               alert(array);
              }
}
//passing numbers:
getNumbers(1, 10, 2);
//output is 1,3,5,7,9

//if your numbers are strings, use:
var min = '1';
var max = '10';
var step = '2';
getNumbers(parseInt(min), parseInt(max), parseInt(step));
//this will work correctly

DEMO

Upvotes: 2

koninos
koninos

Reputation: 5327

Use parseInt to cast to integers

Upvotes: 0

Related Questions