【发布时间】:2016-06-21 13:18:56
【问题描述】:
这个小提琴演示了我的问题:https://jsfiddle.net/petebere/fhg84je2/
我想确保每次用户单击按钮时都会显示数组中的随机元素。问题是有时在进行新的shuffle时,新shuffle的数组中的第一个元素与之前shuffle的数组中的最后一个元素相同。在这些情况下,当用户单击按钮时,会显示相同的元素。然后用户必须再次(或多次)单击该按钮以显示不同的元素。我想避免这种情况。
如果第一个元素等于最后一个元素,我尝试引入 if 语句以再次随机播放,但这似乎不起作用。
非常感谢您的帮助。
HTML 代码:
<div id="container">
<button id="clickHere">Click here to pick a random element from the array</button>
<div id="resultDiv"></div>
</div><!-- container -->
JavaScript 代码:
/* define the array with a list of elements */
var arrayList = [
"1st element in array</br>",
"2nd element in array</br>",
"3rd element in array</br>",
];
/* define the function to shuffle the array */
function shuffleArray() {
for (var i = arrayList.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = arrayList[i];
arrayList[i] = arrayList[j];
arrayList[j] = temp;
}
}
/* execute the shuffleArray function */
shuffleArray();
/* button event initiating the randomiser function */
document.getElementById('clickHere').onclick = function () {
randomiser ();
}
/* populate the resultDiv for the first time */
document.getElementById('resultDiv').innerHTML = arrayList[0];
/* define the array index value for the first click */
var arrayIndex = 1;
/* define the main function */
function randomiser () {
document.getElementById('resultDiv').innerHTML = arrayList[arrayIndex];
arrayIndex = (arrayIndex+1);
if (arrayIndex>arrayList.length-1) {
arrayIndex = 0;
var lastArrayElement = arrayList[arrayList.length-1]
shuffleArray();
var firstArrayElement = arrayList[0];
if (firstArrayElement == lastArrayElement) {
shuffleArray();
}
}
}
编辑 1:
1) SpiderPig 和 2) Jonas-Äppelgran 提出的两种不同的解决方案解决了我的问题。
这是第一个使用push 和shift 方法组合的解决方案的更新小提琴:https://jsfiddle.net/petebere/axatv0wg/
这是第二个解决方案的更新小提琴,它使用while 循环而不是if 语句:https://jsfiddle.net/fhg84je2/2/
两种解决方案都能完美运行,但我更喜欢第二种解决方案,因为我觉得它更容易理解。
【问题讨论】:
-
不确定我是否跟随,但不会从数组中删除您显示的元素以防止它重新出现在您的其他随机播放中吗?
-
如果你发现打乱后的数组的第一个元素和前一个数组的最后一个元素相同,为什么不直接交换打乱后的数组的第一个和最后一个元素呢?您再次调用
shuffleArray()的方法并不能保证新洗牌的数组不会出现同样的问题。
标签: javascript arrays if-statement random shuffle