所以我對 Javascript 還是很陌生,所以我真的不知道這叫什么,反正我想從一個數字中得到“正確的答案”。我嘗試了很多東西并嘗試查找教程,但我找不到它。
這是 JSON 的示例:
{
"questions": [
{
"number": 3,
"question": "?? ? ?? = ?",
"answers": [
"??sunflower",
"BIRTHDAY",
"iPhone",
"MOON CAKE"
],
"correctAnswers": [
"??sunflower"
],
"random": true,
"timeLimit": "24"
},
{
"number": 1,
"question": "?? ? ?? =? ",
"answers": [
"STAR FISH",
"iPhone",
"MOON CAKE",
"HOT DOG"
],
"correctAnswers": [
"STAR FISH"
],
"random": true,
"timeLimit": "20"
},
{
"number": 7,
"question": "?? ? ? = ",
"answers": [
"SUNGLASSES",
"SUNFLOWER",
"HOUSEPAINT",
"IPHONE"
],
"correctAnswers": [
"IPHONE"
],
"random": true,
"timeLimit": 15
},
]
}
我試圖找到“數字”:1,或“問題”中的亂數,然后從該數字中找到“正確答案”。感謝任何幫助,我也在使用純 JS。
uj5u.com熱心網友回復:
const array = {
"questions": [
{
"number": 3,
"question": "?? ? ?? = ?",
"answers": [
"??sunflower",
"BIRTHDAY",
"iPhone",
"MOON CAKE"
],
"correctAnswers": [
"??sunflower"
],
"random": true,
"timeLimit": "24"
},
{
"number": 1,
"question": "?? ? ?? =? ",
"answers": [
"STAR FISH",
"iPhone",
"MOON CAKE",
"HOT DOG"
],
"correctAnswers": [
"STAR FISH"
],
"random": true,
"timeLimit": "20"
},
{
"number": 7,
"question": "?? ? ? = ",
"answers": [
"SUNGLASSES",
"SUNFLOWER",
"HOUSEPAINT",
"IPHONE"
],
"correctAnswers": [
"IPHONE"
],
"random": true,
"timeLimit": 15
},
]
};
const { questions } = array;
// Find by number
const correctAnswersByNumber = qNumber => {
const q = questions.find(({ number }) => number === qNumber);
if (!q) {
return false;
}
return q.correctAnswers;
};
console.log(correctAnswersByNumber(3)); // Question by number === 3
// Random question
const randomCorrectAnswers = questions[Math.floor(Math.random() * questions.length)].correctAnswers;
console.log(randomCorrectAnswers);
uj5u.com熱心網友回復:
使用隨機選擇一個隨機問題。然后顯示正確的屬性。
var data = {
"questions": [
{
"number": 3,
"question": "?? ? ?? = ?",
"answers": [
"??sunflower",
"BIRTHDAY",
"iPhone",
"MOON CAKE"
],
"correctAnswers": [
"??sunflower"
],
"random": true,
"timeLimit": "24"
},
{
"number": 1,
"question": "?? ? ?? =? ",
"answers": [
"STAR FISH",
"iPhone",
"MOON CAKE",
"HOT DOG"
],
"correctAnswers": [
"STAR FISH"
],
"random": true,
"timeLimit": "20"
},
{
"number": 7,
"question": "?? ? ? = ",
"answers": [
"SUNGLASSES",
"SUNFLOWER",
"HOUSEPAINT",
"IPHONE"
],
"correctAnswers": [
"IPHONE"
],
"random": true,
"timeLimit": 15
},
]
};
// Let's choose a random question
let question = data['questions'][Math.floor(Math.random() * data['questions'].length)];
console.log(question.question, question.correctAnswers)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/472968.html
標籤:javascript json
