-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.

5
  • Then don’t call Math.random etc. inside the function… Commented Apr 4, 2021 at 7:52
  • What are you trying to achieve? Commented Apr 4, 2021 at 7:52
  • random_Card() , random_Card() , random_Card() ... i'm Trying to get the same output no matter how many times i execute the random_Card() function in the page . Commented Apr 4, 2021 at 8:02
  • You want a random function returning a not random output? What is the point in it? Commented Apr 4, 2021 at 8:11
  • If you want the number to be random only the first time, you need to store it somewhere, maybe in a closure Commented Apr 4, 2021 at 17:43

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 .
@B14ckDz That’s an unrelated problem which could have any number of causes. But first: document.write is not recommended for DOM manipulations, as it is obsolete, slow and not suitable for any evolving application. See the documentation about the DOM API on MDN 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.
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;
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.