繁体   English   中英

将数据从本地文件读取到 javascript 对象数组

[英]Reading data from local file to javascript array of objects

我有一个测验应用程序,它显示多项选择题。 目前,我所有的问题都硬编码在我的 game.js 文件中名为 questions[] 的数组中。 我想修改我的 game.js 文件,以便所有问题及其选择和答案都从 game.js 文件所在的同一根文件夹中的文本、csv 或 excel 文件中读取。

文本文件将包含以下数据:


问题,选择1,选择2,选择3,选择4,答案

你叫什么名字?,阿里,诺曼,艾哈迈德,丹,诺曼

你最喜欢的科目是什么?,数学,物理,计算机,英语,计算机

什么是2加2?五、六、七、四、四


而我的 game.js 文件如下:

 const question = document.getElementById("question"); const choices = Array.from(document.getElementsByClassName("choice-text")); let currentQuestion = {}; let acceptingAnswers = false; let score = 0; let questionCounter = 0; let availableQuesions = []; 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 } ]; const CORRECT_BONUS = 10; const MAX_QUESTIONS = 3; startGame = () => { questionCounter = 0; score = 0; availableQuesions = [...questions]; console.log(availableQuesions); getNewQuestion(); }; getNewQuestion = () => { if (availableQuesions.length === 0 || questionCounter >= MAX_QUESTIONS) { return window.location.assign("/end.html"); } questionCounter++; const questionIndex = Math.floor(Math.random() * availableQuesions.length); currentQuestion = availableQuesions[questionIndex]; question.innerText = currentQuestion.question; choices.forEach(choice => { const number = choice.dataset["number"]; choice.innerText = currentQuestion["choice" + number]; }); availableQuesions.splice(questionIndex, 1); console.log(availableQuesions); acceptingAnswers = true; }; startGame(); choices.forEach(choice => { choice.addEventListener("click", e => { if (!acceptingAnswers) return; acceptingAnswers = false; const selectedChoice = e.target; const selectedAnswer = selectedChoice.dataset["number"]; console.log(selectedAnswer); getNewQuestion(); }); });

使用fs读取文件。 我建议您使用 JSON 文件来存储数据,这样会更容易处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM