vendredi 24 août 2018

Function to create new array producing undefined

I am trying to write a program that creates an array and populates it with a range of numbers. The function range's x, y, z variables correlates to the start number, the end number, and the number value of each step. My goal is produce an array with all the numbers between (and including) x and y that is created with each step. Here is the code:

let newarray = []

function range (x, y, z){
  if (x === undefined || y === undefined || z === undefined || (x > y) || (z < 0)) {
    return newarray;                          // returns empty array if x, y, or z is undefined, x is greater than y or z is a negative integer
  }
  else if (y > x) {
    for (x; x < y; x = x += z) {
      newarray.push(x);                       //pushes x into an array then adds z into x and loops until x exceeds y
    }
  } 
  else {
    return newarray;                          //prints out new array
  }
}

console.log(range(0, 10, 2));
console.log(range(10, 30, 5));
console.log(range(-5, 2, 3));

right now it is producing undefined for all three numbers. My research suggests something about asynchronicity? I'm not sure what that means.

Aucun commentaire:

Enregistrer un commentaire