Alex Motor
Alex Motor

Reputation: 59

issue with searching through an array and storing the result on a new array

I am trying to create a coin flip game, however I am trying to do things a bit different than what I have seen others do with their code. Essentially I want to store the possible outcomes of a coinflip in an array called before and then create a function that searches through that array and pushes the value of the result of the coin flip into a new array called after. Here is my code so far, but I am getting an error when I am trying to run it.

var before = ["heads" , "tails"];
var after = []

function coinFlip() {
  let repeat = 1
  for (let i = 0; i <= repeat; i++) {
after.push(before[Math.floor(Math.random() * before.length)])

  }
}
coinFlip() //call function
console.log(after);

Upvotes: 0

Views: 45

Answers (1)

Isaac
Isaac

Reputation: 12874

var before = ["heads" , "tails"];
var after = []

function coinFlip() {
  let repeat = 1
  for (let i = 0; i < repeat; i++) {
    after.push(before[Math.floor(Math.random() * before.length)])
  }
}
coinFlip();
console.log(after);

Two things that you're missing, first is you've defined coinFlip function but forgotten to invoke it. Second is that instead of i <= repeat, it should be i < repeat so that it respect the number of repeats that you've defined in repeat

Upvotes: 1

Related Questions