我正在做一个网站上的随机化评论/测试。我正在使用JS来随机化索引页面onLoad上的测试数据。在我的代码中,我使用一个数组来存储测试数据,然后当页面加载时,我希望它只从数组中随机选择3个评论,并将它们分别写入"review-1“、"review-2”和"review-3“。
我的代码的问题是idk是选择3个不同评论的最好方法,而不是重复同一个评论两次。
var reviews = [
"Thank you Anne for fitting me in yesterday when you realised I was desperate to get the house cleaned before the blinds and curtains were fitted. Marie and Michaela did a great job, leaving it sparkling clean. I will certainly recommend you to anyone who needs a cleaner. That you are so approachable, helpful and friendly is a bonus. - <strong>Rosemary OBoyle</strong>",
"Great job on all the awkward hate to do Jobs! Came home from my holidays and my house was sparkling, highly recommended!! - <strong>Lynne Gardiner</strong>",
"Domestic Angels are angels to me, just left lovely Kelly cleaning my house in preparation for mums arrival, while I chill at hairdressers, thank you to Anne & her team, can\'t recommend them enough - <strong>Julie Magee</strong>"
]
var max = reviews.length;
var id1;
var id2;
var id3;
function getRandomReview(max) {
id1 = Math.floor(Math.random() * Math.floor(max));
id2 = Math.floor(Math.random() * Math.Floor(max));
id3 = Math.floor(Math.random() * Math.Floor(max));
}
function randomJS() {
getRandomReview(max);
document.getElementById("review-1").innerHTML = id1;
document.getElementById("review-2").innerHTML = id2;
document.getElementById("review-3").innerHTML = id3;
}任何建议和帮助都将不胜感激。提前感谢
发布于 2020-08-29 20:02:57
谢谢!
只需对其进行混洗,它就能工作!:)
var reviews = [
"Thank you Anne for fitting me in yesterday when you realised I was desperate to get the house cleaned before the blinds and curtains were fitted. Marie and Michaela did a great job, leaving it sparkling clean. I will certainly recommend you to anyone who needs a cleaner. That you are so approachable, helpful and friendly is a bonus. - <strong>Rosemary OBoyle</strong>",
"Great job on all the awkward hate to do Jobs! Came home from my holidays and my house was sparkling, highly recommended!! - <strong>Lynne Gardiner</strong>",
"Domestic Angels are angels to me, just left lovely Kelly cleaning my house in preparation for mums arrival, while I chill at hairdressers, thank you to Anne & her team, can\'t recommend them enough - <strong>Julie Magee</strong>",
]
var max = reviews.length;
var id1;
var id2;
var id3;
function shuffle(reviews) {
reviews.sort(() => Math.random() - 0.5);
}
function randomJS() {
shuffle(reviews);
document.getElementById("review-1").innerHTML = reviews[0];
document.getElementById("review-2").innerHTML = reviews[1];
document.getElementById("review-3").innerHTML = reviews[2];
}https://stackoverflow.com/questions/63646610
复制相似问题