RogerFedFan
RogerFedFan

Reputation: 566

Loop Is Repeating Same Values

I'm trying to create a function where I have 3 parameters: start, step and stop. These will set the start of the loop, how much to go up by and when to stop.

I managed to make it show however the loop is repeating the same numbers until it finishes the task.

I need to show the result in an array so for example if I have a starting position at 0, going up by 2 and stopping at 10, I would to return [0,2,4,6,8,10].

function range(start, step, stop) {

  var rando = [];
  
  for (i = start; i <=stop; i = i + step) {
  
    rando.push(i);
    console.log(rando);
  }
}

range(0, 2, 10);

Upvotes: 1

Views: 1775

Answers (4)

mhodges
mhodges

Reputation: 11116

Simply move your console.log statement outside of your for loop:

When you have the log statement inside the loop, it will log out the contents of the array at every iteration. Since you only want to print out the complete array once, put the console.log statement after the for loop has finished.

function range(start, step, stop) {

  var rando = [];
  
  for (var i = start; i <=stop; i = i + step) {
    rando.push(i);
  }
  console.log(rando);
}

range(0, 2, 10);

As many others have mentioned, an additional suggestion for you would be to put the var or let keyword in front of your i variable in your for loop so that you don't accidentally set or override something on the global scope.

Upvotes: 0

You should return the result array and remove the console.log from the for loop.

I'ts a good practice to declare variables by using var or let.

var rando = [];
for (var i = start; i <= stop; i = i + step) {
  rando.push(i);
}
return rando;

Something like this:

function range(start, step, stop) {
  var rando = [];
  for (var i = start; i <= stop; i = i + step) {
    rando.push(i);
  }
  return rando;
}
console.log(range(0, 2, 10));

Upvotes: 1

iPhoenix
iPhoenix

Reputation: 737

Here's your code, broken down:

You are defining a function (as you said) with three parameters, start, step, and stop.

You then create an empty array, rando.

For each number i from start to stop (counting by step), you append i to rando and print out rando.

This causes your array to be printed out more than once, each time with a new number at the end.

To fix this, you have two options, depending on what you want.

  1. Print out the list after the loop.
  2. Print out i inside the loop.

The first result will print out the array when all of the numbers are added, and the second will print out each number sequentially.

Upvotes: 0

lincolnk
lincolnk

Reputation: 11238

you're printing your array every iteration of the loop. let the loop finish, then call console.log

Upvotes: 0

Related Questions