简体   繁体   中英

is there a way to make two elements pick random items from a array but won't be the same item - Javascript

I have created a function where two different elements (randomColor1 and randomColor2) picks a color from the array. But the problem is sometimes both the elements(randomColor1 and randomColor2) pick the same color.

The value of both the element comes the same.

Here are my codes. Can you please tell me what is the exact code to rectify the issue. I want both elements selects different colors every from each other. I am new to javascript.

function GetValue() {
  var myarray = new Array("#ff0000", "#ffe100", "#95ff00", "#2c8d94","#911961");

  var randomColor1 = myarray[Math.floor(Math.random() * myarray.length)];
  var randomColor2 = myarray[Math.floor(Math.random() * myarray.length)];
  
  document.getElementById("message").innerHTML = randomColor1 + randomColor2;
}

Just remove the element that you are taking out of the array, to ensure you won't pick the same one again:

var randomColor1 = myarray.splice(Math.floor(Math.random() * myarray.length), 1)[0];
var randomColor2 = myarray.splice(Math.floor(Math.random() * myarray.length), 1)[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM