2

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);
            }
3
  • 2
    Make sure your arguments are numbers, not strings. Commented Aug 29, 2014 at 10:02
  • yes if you will give arguments as strings then this problem will come, because the statement i+=step so "2"+="2" will return 22 after that 222 and so on. Commented Aug 29, 2014 at 10:03
  • can you just add a fiddle with your prolem. Commented Aug 29, 2014 at 10:09

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

Use parseInt to cast to integers

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.