gpt4 book ai didi

javascript - 将数组元素插入表 JavaScript/并防止随机数重复

转载 作者:行者123 更新时间:2023-11-28 03:12:00 25 4
gpt4 key购买 nike

我的程序:输入 5 个答案,然后显示包含问题编号、动物、预期答案、提交的答案和结果的表格:

enter image description here

插入 5 个答案后我的表格看起来如何:

enter image description here

问题:

如何使数据每 5 行缩进一次?另外,如何使动物不重复(即如何使从数组中选取动物的 rng 不重复,以便同一动物不会显示两次)

HTML:

<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<style>
#result {
display: none;
}
</style>

<title>Animal Farm</title>
</head>
<body>
<div class='container'>
<h1>Animal Farm</h1>
<h2>Question <span id='question-number'>1</span></h2>
What does the <span id="animal-name">?</span> say?
<select id='user-selection'></select>
<button onclick='recordAnswer()'>Submit</button>


<div id='result'>
<table class='table'>
<thead>
<tr><th>Question</th><th>Animal</th><th>Expected</th><th>You Picked</th><th>Result</th></tr>
</thead>
<tbody id='result-table'>
</tbody>
</table>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="animal.js"></script>
</body>
</html>

JavaScript:

"use strict"

let farm = [] // list of all animals
let currentAnimal = undefined
let theQnum = document.getElementById("question-number")
let questionNumber = 2
let stopCounter = 1
let qArr = []
let animalArr = []
let expectedArr = []
let suppliedAnswers = []
let resultArr = []
let theAnimal
farm = generateAnimalArray()
let theMin = 0
let theMax = farm.length
let theRandom = getRandomInt(theMin, theMax)
let currentSound = farm[theRandom].says
let count = 0
let dropdown = document.getElementById("user-selection")
farm.forEach(x => {
dropdown.innerHTML = `` + dropdown.innerHTML + `` + `<option>${farm[count].says}</option>`
count++
});
let ddVal

showQuestion()


// return a random number in the range [min,max]
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}

// return an animal object
function createAnimal(name, speak) {
return {
type: name,
says: speak
}
}

// generate and return a list of animals in our program
// it is expected that the return value be stored into the "farm" variable
function generateAnimalArray() {
let result = []
result.push(createAnimal('dog', 'woof'))
result.push(createAnimal('cat', 'meow'))
result.push(createAnimal('bird', 'tweet'))
result.push(createAnimal('mouse', 'squeek'))
result.push(createAnimal('cow', 'moo'))
result.push(createAnimal('duck', 'quack'))
result.push(createAnimal('fox', 'ring-ding-ding-ding-dingeringeding'))
return result
}

// Pick a random animal from the list, show it to the user and set the question number
function showQuestion() {
theAnimal = document.getElementById("animal-name")
theAnimal.innerHTML = farm[theRandom].type
}


// Get the answer, create an object with the question number, the animal type, the expected answer and the
// supplied answer and store it into the suppliedAnswer array.
//
// If we have seen 5 questions then show the result, otherwise show the next questions
function recordAnswer() {
ddVal = dropdown.value
qArr.push(questionNumber - 1)
animalArr.push(farm[theRandom].type)
expectedArr.push(currentSound)
suppliedAnswers.push(ddVal)
console.log(ddVal)
if (currentSound != ddVal) {
resultArr.push("Wrong")
}
else {
resultArr.push("Correct!")
}

stopCounter++
if (stopCounter > 5) {
window.recordAnswer = function () { return false; };
console.log(qArr)
console.log(animalArr)
console.log(expectedArr)
console.log(suppliedAnswers)
console.log(resultArr)
displayResult()
}
else {
theRandom = getRandomInt(theMin, theMax)
theAnimal.innerHTML = farm[theRandom].type
theQnum.innerHTML = questionNumber++
ddVal = dropdown.value
currentSound = farm[theRandom].says
}
}

// Show the values in the suppliedAnswers as a table

function displayResult() {
let tableDisplay = document.getElementById("result-table")
let theResult = document.getElementById("result")
theResult.style.display = "block"
qArr.forEach(x => {
tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + x + `</td>`
})
animalArr.forEach(x => {
tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + x + `</td>`
})
expectedArr.forEach(x => {
tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + x + `</td>`
})
suppliedAnswers.forEach(x => {
tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + x + `</td>`
})
resultArr.forEach(x => {
tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + x + `</td>`
})



}

// 1. generate the farm full of animals
// 2. Create the options for the select
// 3. show the first question

document.addEventListener('DOMContentLoaded', () => {
let buffer = []
let strBuff
document.addEventListener('keydown', event => {
const charList = 'abcdefghijklmnopqrstuvwxyz0123456789';
const key = event.key.toLowerCase()
if (charList.indexOf(key) === -1) return;
buffer.push(key)
strBuff = buffer.toString()
if (strBuff == "h,e,l,p") {
window.open('https://www.youtube.com/watch?v=xvypmult19M', '_blank')
buffer = []
strBuff
}
})
})




最佳答案

forEach提供第二个参数,为您提供当前迭代。因此,要每五个项目缩进一次,您可以这样做:

arr.forEach((x, i) => {
if(i % 5 == 0) tableDisplay.innerHTML += "<td style='padding-left:20px;'>" + x + "</td>";
else tableDisplay.innerHTML += "<td>" + x + "</td>";
});

为了防止从数组中选取项目时出现重复,您应该对数组进行打乱,然后 pop()如果您用完值,请重新填充它。这是一个例子:

var arr = [1, 2, 3, 4, 5];
var shuffledArr = randoSequence(arr);

for(var i = 0; i < 10; i++){
if(shuffledArr.length == 0) shuffledArr = randoSequence(arr);
console.log(shuffledArr.pop().value);
}
<script src="https://randojs.com/1.0.0.js"></script>

此示例使用 randojs.com 对数组进行打乱顺序为了简化随机性并使其更具可读性,因此如果您想使用此代码,请确保它位于 html 文档的 head 标记的顶部:

<script src="https://randojs.com/1.0.0.js"></script>

关于javascript - 将数组元素插入表 JavaScript/并防止随机数重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60019046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com