0

When I run this code in JSbin the cardList "card" object contains random numbers as expected. But when I run it locally the outcome is that that "cards" are all set to "0". I've spent a day trying to figure out why. Any ideas?

By the way the code runs as expected locally if I change the "max" variable in the getRandomInt function to an actual number (getRandomInt comes from here).

var cardList = [];
var randomCardlist = []
var max = 9;


function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function GetRandomCards(max) {
  var randomCardlist = [];
  for (var i = 0; i <= 16; i++) {
    var x = getRandomInt(0, max);
    randomCardlist.push(x);
  }
  randomPositioning(randomCardlist)
}

GetRandomCards(max);



function randomPositioning(randomCardlist) {
  for (var y = 0; y <= 16; y++) {
    cardList.push({
      type: "image",
      position: y,
      card: randomCardlist[y]
    });
  }
  console.log(cardList);
}
nem035
  • 34,790
  • 6
  • 87
  • 99
Jason Allshorn
  • 1,625
  • 1
  • 18
  • 27
  • What do you mean by "the code runs as expected locally if I change the `max` variable in the `getRandomInt` function to an actual number"? It's already the number `9`? – nem035 Aug 25 '16 at 13:57
  • http://stackoverflow.com/a/500459/2923632 Check this answer to see exactly why `var randomCardlist = [];` is not functioning as expected. – KnightHawk Aug 25 '16 at 14:05
  • 1
    One *potential* issue I see is you have a local parameter `max` that has the same name as a global variable `max`. –  Aug 25 '16 at 14:08
  • @KnightHawk scope shouldn't be an issue. Its re-declared locally but is passed as a parameter. If it were scope, OP would have `undefined` instead of all `0`s – Adam Konieska Aug 25 '16 at 14:18
  • `randomCardlist` is passed as a parameter to the `randomPositioning` function, but not the `GetRandomCards` function where it's re-defined. The `max` is also passed as a parameter, but it looks like it is passed all the way from the original value. – KnightHawk Aug 25 '16 at 14:24

0 Answers0