0

I'm trying to set values in an array (ansArr), in a random order. The positions are in the pos array, and each position that comes up in the random number is deleted from pos. For some reason, it's not working. I'm quite new to JS, hope this code makes any sense...

var _ans1="ANS1"
var _ans2="ANS2"
var _ans3="ANS3"
var _ans4="ANS4"

var pos = [0,1,2,3]; // array of positions
var ansArr = [_ans4, _ans4, _ans4, _ans4]; // _ans1-_ans3 will run over 3 of the _ans4's
var rand = Math.floor(Math.random() * 4); // 0-3 
posTMP = pos[rand]; 
ansArr[posTMP]= _ans1;

pos.splice(pos[rand,1]); // delete the occupied position

rand = Math.floor(Math.random() * 3); // 0-2
posTMP = pos[rand];
ansArr[posTMP]= _ans2;
pos.splice(pos[rand,1]); // delete the occupied position

rand = Math.floor(Math.random() * 2); // 0-1
posTMP = pos[rand];
ansArr[posTMP]= _ans3;

alert (ansArr[0],ansArr[1],ansArr[2],ansArr[3]);

Thank you very much :)

David
  • 208,112
  • 36
  • 198
  • 279
user3289092
  • 129
  • 1
  • 3
  • you're using splice incorrectly. it's `pos.splice(rand,1)` – Always Learning Apr 20 '20 at 11:42
  • Note that "it's not working" doesn't tell us much about the problem you're observing. There are only a few lines of code here. "Not working" is an opportunity for you to step through the code in a debugger (modern web browsers have debugging tools available) and observe the behavior and result of each line of code. When you do that you can find the very first line of code which produces an unexpected result. Focus on specifically that operation. What were the values? What was the result? What result did you expect? Why? – David Apr 20 '20 at 11:43

0 Answers0