我试图从同一个数组生成两个随机单词。现在这个脚本将选择一个单词,但当我尝试选择两个单词时,我遇到了一个问题。这是问题所在。用户可以选择从复选框中选择多种语言,因此当我将其设为两个单词时,这两个单词使用不同的语言(它们来自不同的列表)。我想确保所选的两个单词来自同一个列表。我该怎么做?
function word(){
var choice = [];
choice[0] = list0[Math.floor(Math.random()*list0.length)];
choice[1] = list1[Math.floor(Math.random()*list1.length)];
choice[2] = list2[Math.floor(Math.random()*list2.length)];
choice[3] = list3[Math.floor(Math.random()*list3.length)];
var final_words = [];
var checkbox = document.getElementsByClassName('c');
for (var i = 0; i < checkbox.length; i++) {
if (checkbox[i].checked) {
final_words.push(choice[i]);
}
}
var finalword = final_words[Math.floor(Math.random()*final_words.length)];
}
答案 0 :(得分:1)
这是你的意思吗?
list0 = ['compare', 'power', 'random', 'raw', 'nothing', 'practice'];
list1 = ['Comparar', 'energía', 'azar', 'crudo', 'nada', 'práctica'];
list2 = ['comparer', 'puissance', 'aléatoire', 'saveur', 'brute'];
list3 = ['比 ', '较 ', '随 ', '机 ', '的 ', '电 ', '源 ', '没 ', '有 ', '生 ', '实 ', '践 '];
// used to match the lists with the id's of the checkboxes (lanugages)
available_words = {
c1: list0,
c2: list1,
c3: list2,
c4: list3
};
function pickRandom(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function getCheckedCheckboxes() {
var checkboxes = document.getElementsByClassName('c');
var checked_checkboxes = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checked_checkboxes.push(checkboxes[i]);
}
}
return checked_checkboxes;
}
function getRandomWords(lang_id, no_words) {
words = [];
for (var i = 0; i < no_words; i++) {
do {
rand_word = pickRandom(available_words[lang_id]);
} while (words.indexOf(rand_word) >= 0);
words.push(rand_word);
}
return words;
}
function word() {
var words = [];
var checked_checkboxes = getCheckedCheckboxes();
if (checked_checkboxes.length != 0) {
var rand_checkbox = pickRandom(checked_checkboxes);
words = getRandomWords(rand_checkbox.id, 2);
}
document.getElementById('q').innerHTML = words.join(' ');
}