Adam Tomczyk
Adam Tomczyk

Reputation: 1

Looping a javascript function and pushing the result into an array

I am at the end of my wits. Maybe somebody can shed some light. I am essentialy trying to run a function 10x using a for loop and then push the results into an array. However, all I get is ten "undefined" in my array. The actual resolved value from the function is not being pushed into array. Does anyone have an idea?

Here's the code

function playGame(){
 var userChoice = getUserChoice('rock');
 var computerChoice = getComputerChoice();
 
  console.log(determineWinner(userChoice,computerChoice));
};

function keepScore () { 
let resultArray = [];

  for(let x = 0; x < 10; x++){
    resultArray.push(playGame(x))
  }
  
   console.log(resultArray); 

};

keepScore();

Thanks in advance

Upvotes: 0

Views: 103

Answers (3)

sample
sample

Reputation: 412

This should work. The main thing here is to return the value wanted. The added code is just to make the snippet work.

function playGame() {
  var options = ['rock', 'paper', 'scissor'];
  var userChoice = window.prompt("rock, paper, scissors");
  var computerChoice = options[(Math.floor(Math.random() * 3  + 1) - 1)];
  var arr = [userChoice, computerChoice];
  console.log(userChoice, computerChoice);
  return (arr);
};

function keepScore() {
  var resultArray = [];
  for (let x = 0; x < 10; x++) {
    resultArray.push(playGame(x))
  }
  console.log(resultArray);
};

keepScore();

Upvotes: 1

Ollie
Ollie

Reputation: 47

You need to return determineWinner(userChoice,computerChoice)

Right now, the function just returns undefined

So, just add return determineWinner(userChoice,computerChoice);, and you should be fine.

Upvotes: 0

Samuel Sorial
Samuel Sorial

Reputation: 228

When you call push, you need to specify an element to be pushed. However, you are calling the play game function which doesn't return any element. You should explicitly specify the element to be returned in the play game and it should work!

function playGame(){
 var userChoice = getUserChoice('rock');
 var computerChoice = getComputerChoice();
 
  return determineWinner(userChoice,computerChoice);
};

Upvotes: 0

Related Questions