John
John

Reputation: 1665

adding random value to array and comparing first two value js

I am trying to learn some simple things in js, so what i am trying to achieve is every time I get a random number I want to add it inside an array at he front, then compare the first two values make sure they are not [6,6]

function randomNumber() {
  number = Math.floor((Math.random() * 6) + 1);
  return number;
}

function addValue() {
  var score = [];
  score.unshift(randomNumber());
  console.log(score);
  return score;
}

At the moment what is happening, every time i call the randomNumber the array only stores one value, it does not append it to the list and overweights the previous.

What am I doing wrong and why is it working? thx

Upvotes: 0

Views: 40

Answers (1)

Nick Timmer
Nick Timmer

Reputation: 425

the variable you use to store the array needs to be created and passed through the argument list, or stored globally. when you do var x = [] you are create a NEW empty array.

  var score = [];
  
  addValue(score);
  addValue(score);
  addValue(score);

function randomNumber() {
  number = Math.floor((Math.random() * 6) + 1);
  return number;
}

function addValue(score) {

  score.unshift(randomNumber());
}

console.log(score)

Upvotes: 2

Related Questions