2016-04-24 4 views
0

Я делаю онлайн-тест, используя Javascript. Я организовал проход банк как массив, и как вы можете видеть это беспорядок (извините за стену коды):Лучший способ управлять большим количеством жестко закодированных данных в моем коде?

var passageBank = [ 
     ["Passage 1", //Passage Title 
     '<p>In 1960, Dr. George Sperling asked participants to recall a 4x3 group of letters flashed on a screen for less than a second. When instructed to recall as many letters as possible, most participants could only name the first four or five letters.</p><p>Dr. Sperling then asked another group to name only one of the rows. After they saw the image flash, he would randomly sound one of three tones. Sounding a high-frequency tone indicated that the participant should give the first line of letters; a medium-frequency tone indicated the middle row; and a low-frequency tone asked for the last row. If the tone was broadcast immediately after the image was flashed, the majority of subjects recalled all four letters. This marked the discovery of iconic memory, the visual form of sensory memory. Audible sensory memory (also known as echoic memory) lasts for several seconds.</p><div id="figure"><img src="https://ka-perseus-images.s3.amazonaws.com/a7d4238a28e6eef5321d3f6278fb17ce5a9461cf.png"></div><b>Figure 1</b><span id="figure">Experimental setup for Dr. Sperling</span><p>Sensory memory is constantly processing enormous amounts of information from the world around you. What you pay attention to gets passed into working memory. This stage can be described in three major sections – the visuospatial sketchpad, the phonological loop, and the central executive. The sketchpad stores visual information, like a photograph, while the loop deals with words and numbers. The job of coordinating the two falls to the central executive – connecting an address you hear with a map that you see, for example.</p>', //Passage with Formatting 
     [[/*Array of Questions*/ 
     /*Question 1*/ 
     "Why did Dr. Sterling use a tone to indicate the line of the row he wanted participants to recite?", 
     /*A*/ 
     "Asking verbally would take longer than iconic memory lasts", 
     /*B*/ 
     "Dr. Sperling intended to study the connection between audio and visual cues", 
     /*C*/ 
     "It was the clearest way to signal the question to multiple participants", 
     /*D*/ 
     "Using an audible cue helped trigger echoic memory", 
     /*Answer*/ 
     "A", 
     /*Student Answer*/ 
     "X", 
     /*Solution*/ 
     "The tones were part of the second round of the experiment.<br><br>Iconic memory is thought to last only a fraction of a second.<br><br>In order to test iconic memory, Dr. Sperling required a stimulus that was quick enough that the image would still be in participants heads." 
     ], 
     [/*Question 2*/"Which is the best test of echoic memory?","Asking participants to provide the next line in a well-known song","Asking participants to summarize a story that was read to them", "Asking participants to identify whether two tones are identical", "Asking participants to sing the first line of their favorite song", "C", "X", "Echoic memory is a form of sensory memory - it is very short-lived.<br><br>Echoic memory is an audible fragment of the information we are continually processing from the outside world.<br><br>Asking participants to identify whether two tones are identical is the best test of echoic memory."], 
     [/*Question 3*/"Which of the following explains why we see movement in a flip-book or stop-motion animation?", "Iconic memory","Central executive", "Echoic memory", "Visuospatial sketchpad", "A", "X", "Flip-books and stop-motion animations are both series of still images flashed in front of the eyes in quick succession to create a moving image.<br><br>The central executive is responsible for coordinating the visuospatial sketchpad and the phonological loop.<br><br>Iconic memory is a major part of change detection, and helps us notice the changes in each progressive image, turning it into a single moving picture."], 
     [/*Question 4*/"If you drive by a stop sign and then try to recall it several minutes later, which are you using?", "Echoic memory, then the phonological loop","Echoic memory, then the visuospatial sketchpad", "Iconic memory, then the visuospatial sketchpad", "Iconic memory, then the phonological loop", "D", "X", "Information passes through the sensory memory to the working memory.<br><br>A stop sign is a picture of a word.<br><br>The stop sign (a picture of a word) would first pass through the iconic memory, and then into phonological loop."], 
     [/*Question 5*/"Which of the following is a technique used to increase the amount of information stored in working memory?","Semantic Networking","Imagery", "Self-referencing","Chunking","D", "X", "Many mnemonic techniques are focused on transferring information from working memory to long-term memory.<br><br>Semantic networks are like mental maps in our heads where we connect related concepts.<br><br>Chunking is the process of grouping information to reduce the number of “datums” stored, to allow for a greater amount of information to be stored in working memory. Ex: remembering TVFBIHPCBS as TV FBI HP CBS."]], 
     ]] 

Это работает, но это раздражает ссылки и понимать в контексте. Мой брат разумно указал, что это, вероятно, лучше организовано в формате, подобном словарю. (Для всех вас педантов - видимо, Javascript на самом деле не имеют словарей Но то, что это кажется достаточно близко?)

Я пытался сделать что-то вроде этого:

var passageBank = { 
     'Passage 1': '<p>In 1960, Dr. George Sperling asked participants to recall a 4x3 group of letters flashed on a screen for less than a second. When instructed to recall as many letters as possible, most participants could only name the first four or five letters.</p><p>Dr. Sperling then asked another group to name only one of the rows. After they saw the image flash, he would randomly sound one of three tones. Sounding a high-frequency tone indicated that the participant should give the first line of letters; a medium-frequency tone indicated the middle row; and a low-frequency tone asked for the last row. If the tone was broadcast immediately after the image was flashed, the majority of subjects recalled all four letters. This marked the discovery of iconic memory, the visual form of sensory memory. Audible sensory memory (also known as echoic memory) lasts for several seconds.</p><div id="figure"><img src="https://ka-perseus-images.s3.amazonaws.com/a7d4238a28e6eef5321d3f6278fb17ce5a9461cf.png"></div><b>Figure 1</b><span id="figure">Experimental setup for Dr. Sperling</span><p>Sensory memory is constantly processing enormous amounts of information from the world around you. What you pay attention to gets passed into working memory. This stage can be described in three major sections – the visuospatial sketchpad, the phonological loop, and the central executive. The sketchpad stores visual information, like a photograph, while the loop deals with words and numbers. The job of coordinating the two falls to the central executive – connecting an address you hear with a map that you see, for example.</p>', //Passage with Formatting 
    } 

Но я озадачен о том, как я должны идти о реализации вопросов. Я чувствую, что мне нужен словарь в словаре; если я просто использую массивы, то это своего рода поражение, чтобы даже сделать это.

Кстати, если вам интересно о моем тесте here it is.

И да, я понимаю, мое хранилище GitHub беспорядок. Я пытаюсь справиться с этим, но github настолько запутан для меня. Это мой первый реальный проект, и я просто изучаю веревки.

+1

Вы можете использовать массив объектов для всех проходов и вопросов. – Tushar

+0

На что это похоже? –

+0

В JavaScript каждый объект является словарем. Однако они не заказаны. – Bergi

ответ

0
allQuestions = [] 

function question(options, answer, solution, title) { 
this.title = title; 
this.options = options; 
this.answer = answer; 
this.solution = solution; 
allQuestions.push(this) 
} 

Для того, чтобы добавить вопросы:

new question(options, answer, solution, title); 

И использовать эту структуру в JavaScript просто обратитесь к элементу массива, например, как Вопросы Название:

allQuestions[0].title 
+0

Просьба уточнить, этот ответ говорит вам о структуре и способах создания Q, но не показывает, как ее использовать. Хорошие усилия в детализации ответов помогут вам получить еще много очков. –

+1

@noideawhattodo: Это не догмы, и это ничего личного, они просто лучшие практики. Я пытаюсь помочь вам улучшить ваш ответ, я не могу вас заставлять, конечно, но не ожидайте, чтобы получить много стимулов для этого. – Bergi

+0

@noideawhattodo вы не можете зарабатывать очки, комментируя !! Этот сайт - дружелюбное место, вы действительно грубы! Я пытался рассказать вам, как вы можете получить больше баллов с подробными ответами. Вы создаете экземпляры в своем ответе, но не показываете, как их использовать. –

3

Перед говоря о структуре данных, я бы предложил вам узнать о the MVC pattern. Вы разрабатываете веб-приложение, тогда это хороший образец в вашем случае. Это может помочь решить вашу проблему.

Цель MVC, чтобы отделить различные вещи в вашем коде:

  • Model является частью приложения, которое обрабатывает данные.
  • View - это часть приложения, которое обрабатывает отображение данных.
  • Controller - это часть приложения, которое обрабатывает взаимодействие пользователя.

В вашем случае, мы можем определить 3 части:

  • Ваш массив жестких закодированных строк должны быть обработаны с помощью модели.
  • Ваш пользовательский интерфейс должен обрабатываться представлением.
  • Ваши взаимодействия с викторинами должны обрабатываться контроллером.

Как только у вас будет хорошее разделение кода, вам будет проще реорганизовать структуру ваших данных (массив, объект, массив объектов ...) или изменить источник этих данных (внешний файл, внешний сторонний API, базу данных ...). Вам просто нужно изменить логику внутри модели, не рефакторируя все приложение.

После этого, мой следующий совет будет состоять в том, чтобы извлечь все ваши данные из вашего кода. Хранить ваши строки в базе данных может быть хорошо (см. T30's answer), но для начала вы могли бы хранить ваши данные в простых JSON file. Тема загрузки JSON-файла из JavaScript хорошо освещена (например, How to use a JSON file in javascript).

И, наконец, я бы реорганизовал вашу структуру данных с помощью массива объектов. Каждый элемент массива будет проходом (проход1, проход 2 ...), и каждая пара ключевого значения в объекте будет элементом прохода (название, текст, вопросы, ответы ...) , Что-то вроде:

[ 
    { 
     "title": "Passage 1", 
     "text": "…", 
     "questions": [ 
      { 
       "label": "…", 
       "choices": ["…"], 
       "answer": "…", 
       "solution": "…" 
      }, 
      { ... }, 
      { ... } 
     ] 
    }, 
    { 
     "title": "Passage 2", 
     ... 
    }, 
    { 
     "title": "Passage 3", 
     ... 
    } 
] 

Чтобы помочь вам преобразовать ваш массив действительного объекта JSON, вы можете проверить его непосредственно в консоли браузера, вызвав JSON.parse(data). Вы увидите, может ли функция проанализировать его или получить некоторые синтаксические ошибки.