我有一个问题,我无法让JS始终打印出3个不同的值,有时它会选择重复的值。有人可以帮忙吗?
var receivedArray = JSON.parse('<?php echo json_encode($unserialize);?>');
const random = receivedArray;
const correctAnswer = random[Math.floor(Math.random() * random.length)];
const guess1 = random[Math.floor(Math.random() * random.length)];
const guess2 = random[Math.floor(Math.random() * random.length)];
$(document).ready(function() {
$("#test-div").append(
"<div class=\"row\">\n" +
"<div class=\"col-6\">\n" +
"<img id=\"testImage\" src=\"\" alt='...' height=\"540px\"/>\n" +
"</div>\n" +
"<div class=\"col-6\">\n" +
"<h4 class=\"Guess\" id=\"Guess\">ATMINI JŪRNIEKU MEZGLA NOSAUKUMU</h4>\n" +
"<div id=\"shuffle\">" +
"<div class=\"btn guesses\" >" + correctAnswer.nameLV + "</div><br>" +
"<div class=\"btn guesses\" >" + guess1.nameLV + "</div><br>" +
"<div class=\"btn guesses\" >" + guess2.nameLV + "</div>" +
"</div>\n" +
"</div>\n" +
"</div>\n"
);
$("#testImage").attr("src", "../Images/uploads/" + correctAnswer.Image);
console.log("BS")
});
答案 0 :(得分:1)
无论何时选择答案,都应使用splice()从random
数组中删除项目:
const correctAnswer = random.splice(Math.floor(Math.random() * random.length), 1);
const guess1 = random.splice(Math.floor(Math.random() * random.length), 1);
const guess2 = random.splice(Math.floor(Math.random() * random.length), 1);
答案 1 :(得分:1)
随机排列数组,然后选择前三个值
const [correctAnswer, guess1, guess2] = shuffle(random);
采取shuffle function here或使用lodash shuffle
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
答案 2 :(得分:0)
是的,如果它只是多次从列表中选择一个随机项目,那有时会随机选择同一项目。
您可以代替的是,一旦被随机选择,请删除该项目。如果以后需要访问原始阵列,可以先复制阵列。
const random = [...receivedArray]; //copy
const correctAnswer= random.splice(Math.floor(Math.random() * random.length),1)[0];
const guess1 = random.splice(Math.floor(Math.random() * random.length),1)[0];
const guess2 = random.splice(Math.floor(Math.random() * random.length),1)[0];
Splice删除并返回指定数量的项目。您看到的第二个参数是要删除的数字,在您的情况下为1。Splice返回一个数组(甚至是一项的数组),因此您必须添加[0]才能访问该项本身。
由于该项目将被删除,因此无法再次猜测!简单!
答案 3 :(得分:0)
randojs.com为此提供了一个简单易读的随机播放功能。只需使用该randoSequence
函数和pop进行改组即可获取您的值
var array = ["one", "two", "three"];
var shuffled = randoSequence(array);
console.log(shuffled.pop().value, shuffled.pop().value);
<script src="https://randojs.com/1.0.0.js"></script>