下面我創建了兩個循環。循環返回非常長的數組,即使它循環3次?
基本上它首先循環通過隨機數組,包含4個值。然後隨機生成一個介於0和3之間的數字,並從隨機數組中選擇一個值到console.log以隨機順序返回(For例如2,0,3,1)。
下一個循環正在隨機創建錯誤答案。如果這個錯誤的答案不存在於allAnswers數組中,它會將其推送到數組中。
然後循環並創建一個按鈕,這將是用戶可以選擇的答案。
這一切都很完美。除了我的allAnswers數組返回13個值時,它應該只有4個(其中1個是我的預定值21)。
我需要它創建4個按鈕,每個按鈕都通過0-3之間的數組位置來回答並返回這些唯一值,而不會說明未定義的值。所以我不確定在這種情況下我做錯了什麼?
var allAnswers = [21],
randomizer = [0, 1, 2, 3],
random = 0,
buttonArea = $("#answerOptions");
for (randomizer, r = randomizer.length; r--;) {
random = randomizer.splice(Math.floor(Math.random() * (r + 1)), 1)[0];
// console.log(random);
// Generates 3 random wrong answers
for(wa = 0 ; wa < 3; wa++) {
wrongAnswers = Math.floor((Math.random() * 100) + 1);
}
// Pushes wrong answers to array
if (allAnswers.indexOf(wrongAnswers) === -1) {
allAnswers.push(wrongAnswers);
}
console.log(random);
input = $('<div class="col-xs-6"><button class="btn btn-primary answerButton">'+ allAnswers[random] +'</button></div>');
input.appendTo(buttonArea);
}
console.log(allAnswers);
編輯:
添加新的循環,建議
var goodAnswer = 21,
allAnswers = [],
wrongAnswer,
wa,
buttonArea = $("#answerOptions");
for(wa = 0; wa < 4; wa++) {
do {
wrongAnswer = Math.floor((Math.random() * 100) + 1);
} while(wrongAnswer == goodAnswer || allAnswers.indexOf(wrongAnswer) !== -1);
allAnswers.push(wrongAnswer);
input = $('<div class="col-xs-6"><button class="btn btn-primary answerButton">'+ allAnswers +'</button></div>');
input.appendTo(buttonArea);
}
allAnswers[Math.floor(Math.random() * 4)] = goodAnswer;
console.log(goodAnswer);
console.log(allAnswers);
console.log(wa);
並不需要很長時間,需要小於5ms - > https://jsfiddle.net/zsyuxph7/ –
,如果你還刪除'的console.log()'在你的代碼的中間需要少於2ms - > https://jsfiddle.net/zsyuxph7/1/ –
我確實看到那些循環返回未定義值的情況嗎? :) –