【问题标题】:Select and show items from an array选择并显示数组中的项目
【发布时间】:2022-12-11 16:31:14
【问题描述】:

我是 Web 开发的新手,并试图通过将自己的想法变为现实来学习东西。现在我试图做一个测验,其中包含来自数学、科学、语言等多个学科的问题。我的测验包含 50 个问题和来自 5 个不同部分的 10 个问题。我试图将我的问题添加到 5 个不同的数组中,并尝试从每个部分中随机选择 10 个问题。我不知道该怎么做。我希望你们中的任何一个都能提供帮助。我正在按照 YouTube 教程来构建它。

游戏.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Let's Play</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="game.css">
</head>
<body>
    <div class="container">
        <div id="game" class="justify-center flex-column">
            <div id="hud">
                <div id="hud-item">
                    <p class="hud-prefix">
                        Question
                    </p>
                    <h1 class="hud-main-text" id="questionCounter">
                        
                    </h1>
                </div>

                <div id="hud-item">
                    <p class="hud-prefix">
                        Score
                    </p>
                    <h1 class="hud-main-text" id="score">
                        0
                    </h1>
                </div>
            </div>
            <h2 id="question">What is the answer to this question?</h2>
            <div class="choice-container">
                <p class="choice-prefix">A</p>
                <p class="choice-text" data-number="1">Choice 1</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">B</p>
                <p class="choice-text" data-number="2">Choice 2</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">C</p>
                <p class="choice-text" data-number="3">Choice 3</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">D</p>
                <p class="choice-text" data-number="4">Choice 4</p>
            </div>
        </div>
    </div>
    <script src="game.js"></script>
</body>
</html>

游戏.js


const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
const questionCounterText = document.getElementById('questionCounter');
const scoreText = document.getElementById('score');

let currentQuestion = {};
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuestions = [];

let questions = [
    {
        question: 'Inside which HTML element do we put the JavaScript??',
        choice1: '<script>',
        choice2: '<javascript>',
        choice3: '<js>',
        choice4: '<scripting>',
        answer: 1,
    },
    {
        question:
            "What is the correct syntax for referring to an external script called 'xxx.js'?",
        choice1: "<script href='xxx.js'>",
        choice2: "<script name='xxx.js'>",
        choice3: "<script src='xxx.js'>",
        choice4: "<script file='xxx.js'>",
        answer: 3,
    },
    {
        question: " How do you write 'Hello World' in an alert box?",
        choice1: "msgBox('Hello World');",
        choice2: "alertBox('Hello World');",
        choice3: "msg('Hello World');",
        choice4: "alert('Hello World');",
        answer: 4,
    },
];

///CONSTANTS

const CORRECT_BONUS = 1;
const MAX_QUESTIONS = 3;

startGame = () =>{
    questionCounter = 0;
    score = 0;
    availableQuestions = [...questions];
    getNewQuestion();
};

getNewQuestion = () =>{

    if(availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS){
        localStorage.setItem('mostRecentScore', score);
        //go to end page
        return window.location.assign('/end.html');
    }

    questionCounter++;
    
    questionCounterText.innerText = `${questionCounter}/${MAX_QUESTIONS}`;    
    const questionIndex = Math.floor(Math.random() * availableQuestions.length);
    currentQuestion = availableQuestions[questionIndex];
    question.innerText = currentQuestion.question;
    choices.forEach(choice => {
        const number = choice.dataset['number'];
        choice.innerText = currentQuestion['choice' + number];
    });

    availableQuestions.splice(questionIndex, 1);
    acceptingAnswers = true;
};

choices.forEach(choice =>{

    choice.addEventListener('click', e =>{
        if(!acceptingAnswers) return;
        acceptingAnswers = false;

        const selectedChoice = e.target;
        const selectedAnswer = selectedChoice.dataset['number'];


        const classToApply = 
        selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";

        if(classToApply === 'correct'){
            incrementScore(CORRECT_BONUS);
        }
        
        selectedChoice.parentElement.classList.add(classToApply);

        setTimeout (() => {
            selectedChoice.parentElement.classList.remove(classToApply);
            getNewQuestion();
        }, 1000);

    });

});

incrementScore = num =>{
    score += num;
    scoreText.innerText = score;
}

startGame();

【问题讨论】:

    标签: javascript html web-developer-toolbar


    【解决方案1】:

    这是解决您的问题的 JavaScript 函数:

    // Declare 5 arrays with 20 strings in each array
    let array1 = ["apple", "orange", "banana", "grape", "strawberry", "peach", "lemon", "lime", "mango", "pineapple", "watermelon", "kiwi", "blueberry", "raspberry", "blackberry", "cherry", "papaya", "pear", "coconut", "fig"];
    let array2 = ["dog", "cat", "bird", "fish", "lizard", "turtle", "snake", "hamster", "rabbit", "mouse", "rat", "gerbil", "ferret", "hedgehog", "guinea pig", "chinchilla", "prairie dog", "parakeet", "finch", "canary"];
    let array3 = ["car", "truck", "bus", "van", "motorcycle", "bicycle", "skateboard", "rollerblades", "scooter", "snowmobile", "golf cart", "ATV", "SUV", "boat", "jet ski", "speedboat", "sailboat", "canoe", "kayak", "paddleboard"];
    let array4 = ["red", "orange", "yellow", "green", "blue", "purple", "pink", "brown", "black", "white", "gray", "gold", "silver", "bronze", "copper", "platinum", "bronze", "silver", "gold", "platinum"];
    let array5 = ["pencil", "pen", "marker", "crayon", "colored pencil", "highlighter", "sharpie", "chalk", "pencil sharpener", "eraser", "paper clip", "stapler", "tape dispenser", "glue stick", "scissors", "hole punch", "ruler", "tape measure", "compass", "protractor"];
    
    // Create a function that picks 10 random items from each array and stores them in 5 new arrays
    function pickRandomItems() {
      // Create 5 new arrays
      let newArray1 = [];
      let newArray2 = [];
      let newArray3 = [];
      let newArray4 = [];
      let newArray5 = [];
    
      // Pick 10 random items from each array and store them in the new arrays
      for (let i = 0; i < 10; i++) {
        newArray1.push(array1[Math.floor(Math.random() * array1.length)]);
        newArray2.push(array2[Math.floor(Math.random() * array2.length)]);
        newArray3.push(array3[Math.floor(Math.random() * array3.length)]);
        newArray4.push(array4[Math.floor(Math.random() * array4.length)]);
        newArray5.push(array5[Math.floor(Math.random() * array5.length)]);
      }
    
      // Return the new arrays
      newArrayList = [newArray1, newArray2, newArray3, newArray4, newArray5];
      return newArrayList;
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-07-23
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多