-3

This is the code that I tried:

<script>
    function random_Card() {
      var colors = ["red", "yellow"];
      var result = colors[Math.floor(Math.random() * colors.length)];
      return result;
    }
    
    document.write(
      '<div class="frontface"  style=background-color:' + random_Card() + "></div>"
    );
    document.write(
      '<div class="frontface"  style=background-color:' + random_Card() + "></div>"
    );
</script>

When the variable result is returned it's not the same, for example if I executed random_Card() two times I got 'red' and in the second execution I got 'yellow' but I want it to be the same no matter how many times I execute that function. Thanks.

Som Shekhar Mukherjee
  • 3,348
  • 1
  • 3
  • 19

2 Answers2

0

you can set the index at the beginning of the script.

var index_this_time = Math.floor(Math.random()*2)
function random_Card(){
    var colors = [
        "red",
        "yellow"
    ];
    var result = colors[index_this_time];
    return result;
}
jeme95
  • 21
  • 2
  • it didn't work when i used Math.random() outside the function . . . it keep saying random_Card is not defined in the console each time i execute the function . – B14ck Dz Apr 04 '21 at 08:12
  • @B14ckDz That’s an unrelated problem which could have any number of causes. But first: `document.write` is [not recommended](https://stackoverflow.com/q/802854/4642212) for DOM manipulations, as it is obsolete, slow and not suitable for any evolving application. See [the documentation about the DOM API on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) and use methods and properties that aren’t discouraged. Make sure that your issue isn’t related to `document.write` by replacing it with something else, then edit your post and show the modified code. – Sebastian Simon Apr 04 '21 at 08:32
0

Like said before, this function will always return a random, as it's executed every time. What you could do is execute the function once and then fix it to the created result. The second time the function is called, it will only result the same exact object, without doing any more executions.

var random_Card = function(){
  var colors = [
    "red",
    "yellow"
  ];
  var result = colors[Math.floor(Math.random()*colors.length)];
  random_Card = function() { return result; };
  return result;
};
Kevin Verstraete
  • 766
  • 1
  • 6
  • 10