你能在一个数组中操作一个JS函数吗?

我有 JS 测验,问题是从数组中随机选择的。我试图用图像(俱乐部徽章)替换每个问题,但保持答案格式不变。这可能吗?如何实现?


当前代码如下:


JavaScript


const questions = [

    {

        question:  `What league do Manchester United play in?`,

        answers: [

            {text: 'Premier League', correct: true},

            {text: 'Championship', correct: false},

            {text: 'League One', correct: false},

            {text: 'Scottish Premiership', correct: false}

        ]

    },

    {

        question: 'What league do Millwall play in?',

        answers: [

            {text: 'Premier League', correct: false},

            {text: 'Championship', correct: true},

            {text: 'League One', correct: false},

            {text: 'Scottish Premiership', correct: false}

        ]

    },

HTML:


<div id="question"><img id="crest" src="assets/images/image1.png"></div>

我已经在 JS 中创建了这些函数,但不知道如何让它们在问题中运行


function displayManutdCrest() {

    document.getElementById('crest').src='assets/images/image2.png'

}

function displayMillwallCrest() {

    document.getElementById('crest').src='assets/images/image3.png'

}

我只是在学习 JS,如果这没有意义,我深表歉意


繁花如伊
浏览 117回答 1
1回答

慕容森

我认为这个问题是有道理的,可以说明一些有用的东西。您想要创建一种易于放大的方法。如评论中所述,您不想为每个问题编写一个函数,这会使构建问题库变得非常困难。您需要一个单一的功能来回答任何问题以及您需要的所有信息。那么函数只需要从题库中读取相应的信息即可。您可以添加另一个标签,例如pict. 类似(非功能代码):const questions = [{&nbsp; &nbsp; question:&nbsp; `What league do Manchester United play in?`,&nbsp; &nbsp; pict: "assets/images/image2.png",&nbsp; &nbsp; answers: [&nbsp; &nbsp; &nbsp; &nbsp; {text: 'Premier League', correct: true},&nbsp; &nbsp; &nbsp; &nbsp; {text: 'Championship', correct: false},&nbsp; &nbsp; &nbsp; &nbsp; {text: 'League One', correct: false},&nbsp; &nbsp; &nbsp; &nbsp; {text: 'Scottish Premiership', correct: false}&nbsp; &nbsp; ]},{&nbsp; &nbsp; question: 'What league do Millwall play in?',&nbsp; &nbsp; pict: "assets/images/image3.png",&nbsp; &nbsp; answers: [&nbsp; &nbsp; &nbsp; &nbsp; {text: 'Premier League', correct: false},&nbsp; &nbsp; &nbsp; &nbsp; {text: 'Championship', correct: true},&nbsp; &nbsp; &nbsp; &nbsp; {text: 'League One', correct: false},&nbsp; &nbsp; &nbsp; &nbsp; {text: 'Scottish Premiership', correct: false}&nbsp; &nbsp; ]},...];function displayQuestion(q){&nbsp; // Choose question&nbsp; let i = ... ; //someRandomValue;&nbsp; let question = q[i];&nbsp; //&nbsp; document.getElementById('crest').src = question.pict;}displayQuestion(questions);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript