質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

Q&A

2回答

1242閲覧

JavascriptとHTMLでクイズを作りましたが表示されず困っています。

hunyuchan9800

総合スコア9

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

0グッド

2クリップ

投稿2018/08/07 05:11

編集2022/01/12 10:55

実現してほしい所
JavascriptをHTML上で表示させたいです。

発生した問題
Javascriptでクイズを作っています。
マニュアルに書いてある通りにクイズを作ったので、間違いがないように見えますが、

ReferenceError: can't access lexical declaration `myQuestions' before initialization

と表示されてしまいます。何回も見直しましたが特に間違いだと思うところはありませんでした。
これが全てのコードになります。

Javascript

1const quizContainer = document.getElementById('quiz'); 2const resultsContainer = document.getElementById('results'); 3const submitButton = document.getElementById('submit'); 4function buildQuiz(){} 5 6function showResults(){} 7 8// display quiz right away 9buildQuiz(); 10 11// on submit, show results 12submitButton.addEventListener('click', showResults); 13const myQuestions = [ 14 { 15 question: "Who is the strongest?", 16 answers: { 17 a: "Superman", 18 b: "The Terminator", 19 c: "Waluigi, obviously" 20 }, 21 correctAnswer: "c" 22 }, 23 { 24 question: "What is the best site ever created?", 25 answers: { 26 a: "SitePoint", 27 b: "Simple Steps Code", 28 c: "Trick question; they're both the best" 29 }, 30 correctAnswer: "c" 31 }, 32 { 33 question: "Where is Waldo really?", 34 answers: { 35 a: "Antarctica", 36 b: "Exploring the Pacific Ocean", 37 c: "Sitting in a tree", 38 d: "Minding his own business, so stop asking" 39 }, 40 correctAnswer: "d" 41 } 42]; 43function buildQuiz(){ 44 // we'll need a place to store the HTML output 45 const output = []; 46 47 // for each question... 48 myQuestions.forEach( 49 (currentQuestion, questionNumber) => { 50 51 // we'll want to store the list of answer choices 52 const answers = []; 53 54 // and for each available answer... 55 for(letter in currentQuestion.answers){ 56 57 // ...add an HTML radio button 58 answers.push( 59 `<label> 60 <input type="radio" name="question${questionNumber}" value="${letter}"> 61 ${letter} : 62 ${currentQuestion.answers[letter]} 63 </label>` 64 ); 65 } 66 67 // add this question and its answers to the output 68 output.push( 69 `<div class="question"> ${currentQuestion.question} </div> 70 <div class="answers"> ${answers.join('')} </div>` 71 ); 72 } 73 ); 74 75 // finally combine our output list into one string of HTML and put it on the page 76 quizContainer.innerHTML = output.join(''); 77} 78myQuestions.forEach( (currentQuestion, questionNumber) => { 79 // here goes the code we want to run for each question 80}); 81// we'll want to store the list of answer choices 82const answers = []; 83 84// and for each available answer... 85for(letter in currentQuestion.answers){ 86 87 // ...add an html radio button 88 answers.push( 89 `<label> 90 <input type="radio" name="question${questionNumber}" value="${letter}"> 91 ${letter} : 92 ${currentQuestion.answers[letter]} 93 </label>` 94 ); 95} 96 97// add this question and its answers to the output 98output.push( 99 `<div class="question"> ${currentQuestion.question} </div> 100 <div class="answers"> ${answers.join('')} </div>` 101); 102quizContainer.innerHTML = output.join(''); 103function showResults(){ 104 105 // gather answer containers from our quiz 106 const answerContainers = quizContainer.querySelectorAll('.answers'); 107 108 // keep track of user's answers 109 let numCorrect = 0; 110 111 // for each question... 112 myQuestions.forEach( (currentQuestion, questionNumber) => { 113 114 // find selected answer 115 const answerContainer = answerContainers[questionNumber]; 116 const selector = 'input[name=question'+questionNumber+']:checked'; 117 const userAnswer = (answerContainer.querySelector(selector) || {}).value; 118 119 // if answer is correct 120 if(userAnswer===currentQuestion.correctAnswer){ 121 // add to the number of correct answers 122 numCorrect++; 123 124 // color the answers green 125 answerContainers[questionNumber].style.color = 'lightgreen'; 126 } 127 // if answer is wrong or blank 128 else{ 129 // color the answers red 130 answerContainers[questionNumber].style.color = 'red'; 131 } 132 }); 133 134 // show number of correct answers out of total 135 resultsContainer.innerHTML = numCorrect + ' out of ' + myQuestions.length; 136} 137// gather answer containers from our quiz 138const answerContainers = quizContainer.querySelectorAll('.answers'); 139 140// keep track of user's answers 141let numCorrect = 0; 142// for each question... 143myQuestions.forEach( (currentQuestion, questionNumber) => { 144 145 // find selected answer 146 const answerContainer = answerContainers[questionNumber]; 147 const selector = `input[name=question${questionNumber}]:checked`; 148 const userAnswer = (answerContainer.querySelector(selector) || {}).value; 149 150 // if answer is correct 151 if(userAnswer===currentQuestion.correctAnswer){ 152 // add to the number of correct answers 153 numCorrect++; 154 155 // color the answers green 156 answerContainers[questionNumber].style.color = 'lightgreen'; 157 } 158 // if answer is wrong or blank 159 else{ 160 // color the answers red 161 answerContainers[questionNumber].style.color = 'red'; 162 } 163}); 164// find selected answer 165const answerContainer = answerContainers[questionNumber]; 166const selector = `input[name=question${questionNumber}]:checked`; 167const userAnswer = (answerContainer.querySelector(selector) || {}).value; 168// if answer is correct 169if(userAnswer===currentQuestion.correctAnswer){ 170 // add to the number of correct answers 171 numCorrect++; 172 173 // color the answers green 174 answerContainers[questionNumber].style.color = 'lightgreen'; 175} 176// if answer is wrong or blank 177else{ 178 // color the answers red 179 answerContainers[questionNumber].style.color = 'red'; 180} 181// show number of correct answers out of total 182resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`; 183(function(){ 184 // put the rest of your code here 185})();

問題が発生した箇所

Javascript

1 // for each question... 2 myQuestions.forEach( 3 (currentQuestion, questionNumber) => { 4 5 // we'll want to store the list of answer choices 6 const answers = []; 7

自分なりの対策
何度も見直しました。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

m.ts10806

2018/08/07 05:16

「見直した」は対策ではないと思います。エラーメッセージで調べて具体的にコードに反映する、デバッグをするなど実際に頭と手を動かしてください。人間の目と思い込みほど信用できないものはありません。
hunyuchan9800

2018/08/07 05:19

わかりました。具体的にコードに反映してみます。
guest

回答2

0

基本的にプログラムでエラーが起こったときにはエラー内容に情報が詰まっています。まずはエラーの内容を把握しましょう。エラーメッセージをそのままGoogle翻訳にかけてみます。
「初期化の前に字句宣言 myQuestions にアクセスできません」
怪しい日本語ですがなんとなく意味はわかる感じがします。
エラーの出力行数からもわかりますが、エラーはfunction buildQuiz()内のmyQuestions.forEachで起こっています。
プログラムは基本的に上から下へ実行されていきます。
上から見ていくとまずconstでいくつか定義されており、その後にbuildQuiz();を実行となっており、実際のfunction buildQuiz()の中身を追っていくとmyQuestionsが...ここまでにmyQuestionsは宣言されていませんね?
function buildQuiz()内のmyQuestions.forEachより上にはmyQuestionsが書かれていますが
実際の実行順で考えるとbuildQuiz();で実行される際にはまだmyQuestionsがいないのです。
なので、エラーメッセージの通り、初期化の前にmyQuestionsにアクセスできません。つまりmyQuestionsってなんぞやと言う状態になってるわけですねー。
エラーの解決方法としてはそのままでbuildQuiz();を呼び出す前にconst myQuestionを書いてやる必要があると思われます。

また、プログラムを書く際には一気に書かずにこまめに実行し、動きを試しながら書いていくのが良いと思います。
一気に書いてしまうと最後に実行して動かなかったときにどの部分が悪くて動かないのかがわかりにくくなるためです。
まずはこの動きを作ろうとか、表示されるところを作ろうとか、部分的にやっていくと動かなくても今書いていた部分が影響しているとハッキリわかるので対処がしやすいです。

マニュアル通りに作るにしてもどの部分がどのような動きになるかの意味を追って順に書いていくと良いかと思います。(本当に全てマニュアル通りならば全部一気に書いてしまっても動きそうな感じもしますが・・・)

投稿2018/08/07 06:44

razuma

総合スコア1313

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

そのマニュアルってのはここのことですかね。

何が間違っているか

本文読まずにソースだけ順番にコピペしてること。

一通り記事を読んでみましたが、この記事は先に実装が空のプロトタイプ的なコードを載せ、あとから未実装部分の追加と解説を行うというスタイルでやっているようです。
なので、実装のない殻の関数→関数の中身や修正内容という順番でコードが並んでいて、そのまま順番にコピペしていくとわけのわからないコードになっていきます。
もう一度コードを見返してみてください。妙な重複がいっぱいあるでしょ。

どうすればいいか

文章を読みながらコードを修正していく、のが最も正攻法なんですが、この本文もちょっとわかりにくいかなと感じます。(前のコードのここを直せ、みたいなところまで書いていない)
あまり初心者向けの内容ではないですね。
記事の後半に実際に動くプレイグラウンドがついています。Edit on codepenと書かれてるフレームです。(冒頭にリンクがちゃんとありますよ)
ここに最終的なスクリプトが載っていますので、それをコピーして実際に動かしてみてください。
それで、そのコードと本文を見比べながら、どんな処理をしているのか学習していってください。

おまけ

日本語に翻訳された記事もありました。
公式
あと、関数名やコメントで検索したら同じようなコードがたくさん見つかりました。どれかがオリジナルなんでしょうね。

投稿2018/08/07 22:59

hope_mucci

総合スコア4447

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問