2017-09-04 4 views
0

이것은 내 첫 번째 게시물이기 때문에 어떠한 분규라도 용서해주십시오! 나는 거의 몇 시간 동안이 일을 해왔으므로 나의 연구를 철저히 수행하고 많은 해결책을 시도했다. 나는 또한 프로그래밍에서 새로운 것 같지만 자신을 빠른 학습자로 생각합니다!도전적인 자바 스크립트 비교 문제 (항상 false 반환) | 게시하기 전에 테스트/조사했습니다.

아래 코드에서 this.innerText 값을 페이지에서 클릭 한 "triviaAnswer"변수에서 값을 가져 오는 변수와 비교하는 "buttonClicked"변수를 비교하려고합니다 " arrayOfTrivias [j] .answer "는 triviaArray의 현재 색인 객체에서 해당 값을 가져옵니다.

비록 내가 console.log에서 값과 두 값이 모두 동일한 값으로 표시 될 수 있지만, if 문을 때릴 때마다 모든 버튼이 "triviaAnswer"와 일치하는 false match (일치하는 버튼조차도)를 반환합니다. "또는 비교 속성에 따라"triviaAnswer "에 true match (일치하지 않는 버튼조차도)를 실행합니다.

는 나는 아무 성공 다음 시도

~ 하나/둘 다 바르 (내가 뭔가를 놓친 수도 있지만!) : toString(), indexOf, typeOf

~ 운영자 : ===, ==, .eq()

~ 비교를 위해 두 변수를 빈 문자열에 전달

~ c에서 변수의 위치를 ​​전환하는 중 omparison

내 목표는 클릭 한 버튼에서 문자열 값을 가져 와서 'triviaAnswer'와 일치하는지 확인하는 것입니다.

모든 코드는 내 것입니다 (명백한 CDN 링크 제외).

모든 도움말이 가장 좋습니다. 이 문제를 해결하려는 경우,이 경험을 통해 배우고 자하는 솔루션을 어떻게 찾았는지 설명하십시오! :-)

"On-Click Events"섹션에서 비교 문제가 발생합니다.

자바 스크립트

$(document).ready(function() { 
    //This is the array we will use to store our trivia objects. 
    var triviaArray = []; 

    /** 
    * Set the start of the array. We will also use this to keep track of our 
    * place is the array. 
    * Set it to minus so we can go to the first objext (0) in the array when we 
    * begin. 
    */ 
    var j = -1; 

    //Countdown timer variables 
    var countdownNumber = 60; 
    var intervalId; 

    //button trackers 
    var buttonClicked; 

    //comparison variables 
    var triviaAnswer; 

    //score variables 
    var correctAnswers = 0; 
    var incorrectAnswers = 0; 
    var noAnswers = 0; 

    var triviaObj1 = { 
    question: "What is the highest grossing anime film worldwide?", 
    options: ["Spirited Away", "Howl's Moving Castle", "Your Name", "Pokemon The Movie"], 
    answer: "Your Name" 
    } 
    var triviaObj2 = { 
    question: "What is an Otaku?", 
    options: ["A type of sushi", "A type of anime fan", "A type of bullet train", "A type of bonsai"], 
    answer: "A type of anime fan" 
    } 
    var triviaObj3 = { 
    question: "What is historically the most popular professional sport in Japan?", 
    options: ["Baseball", "Basketball", "Sumo Wrestling", "Marital Arts"], 
    answer: "Baseball" 
    } 
    triviaArray = [triviaObj1, triviaObj2, triviaObj3]; 

    $("#startButton").on("click", function() { 
    // pass the array of triviaObjects to the triviaGenerator 
    triviaGenerator(triviaArray); 

    //Start the countdown/timer 
    countdownTimer(); 

    //Hide start button afterward pressed, we won't need it anymore 
    $("#startButton").hide(); 
    }); 

    // handles the user button clicks 
    $("body").on("click", ".optionButton", function() { 
    buttonClicked = this.innerText; 
    //if user clicks on an option button, run the following 
    if ($(this).parent().attr('id') === "optionsContainer") { 
     console.log("buttonClicked:", buttonClicked); 
     console.log("triviaAnswer:", triviaAnswer); 
     //Run the comparison, check the buttons text and the "answer" from the 
     object. StackOverflow "Problem If Statement Here" 
     if (buttonClicked == triviaAnswer) { 
     alert("CORRECT"); 
     } else { 
     alert("WRONG"); 
     } 
    } 
    }); 

    function countdownTimer() { // this will be our countdown timer. 
    intervalId = setInterval(decrement, 1000); 
    } 

    function decrement() { // The decrement function. 
    countdownNumber--; 
    $("#countdown").html("<h2>" + countdownNumber + "</h2>"); 
    if (countdownNumber === 0) { 
     timesUp(); //run the gameOver function. 
    } 
    } 

    function timesUp() { 
    clearInterval(intervalId); 
    countdownNumber = 60; //reset and restart the countdown. 
    countdownTimer(); 
    triviaGenerator(triviaArray); //move to the next trivia object. 
    } 

    function triviaGenerator (arr) { // We will use this function to generate our array. 
    var arrayOfTrivias = arr; 
    j = j + 1; //Go up one in the array (go to the next object in the array) 
    j = j % arrayOfTrivias.length; // end of the array ? -> go back to the beginning 
    triviaAnswer = arrayOfTrivias[j].answer; //assign the trivia's answer to a global variable so we can do a comparison against the users answer 

    //Print the trivia's question to the page 
    //Make sure the div is clear for the insertion of the trivia's question 
    $("#questionContainer").text(""); 

    //Insert the question for the trivia we are on 
    var triviaQuestion = arrayOfTrivias[j].question; 
    $("#questionContainer").append("<h2>" + triviaQuestion + "</h2>"); 

    var optionsArray = arrayOfTrivias[j].options; 

    // Loop through the options array for this trivia and print//append them as buttons to the screen. 
    $("#optionsContainer").text(""); 
    for (var i = 0; i < optionsArray.length; i++) { 
     $("#optionsContainer").append("<button class='optionButton btn btn-default'>" + "<h2>" + optionsArray[i] + "</h2> </button>"); 
    } 
    } 
}); 

HTML

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Trivia Game</title> 
    <link rel="stylesheet" type="text/css" href="style.css"> 
    </head> 

    <body> 
    <nav class="navbar navbar-inverse header"> 
     <div class="container-fluid"> 
     Header/Navbar here 
     </div> 
    </nav> 
    <div class="container-fluid text-center"> 
     <div class="row content"> 
     <div class="col-sm-2 sidenav"></div> 
     <div class="col-sm-8 left-center"> 
      <p id="welcomeBanner"> Welcome to the Trivia Page</p> 
      <div id="dynamicDiv"> 
      <button id="startButton" class="btn btn-danger center"> 
       Start 
      </button> 
      <div id="countdown"></div> 
      <div id="questionContainer"></div> 
      <div id="optionsContainer"></div> 
      </div> 
     </div> 

     <div class="col-sm-2 sidenav"></div> 
     </div> 
    </div> 
    <footer class="container-fluid text-center footer"> 
     <p> Footer Text </p> 
    </footer> 
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> 
    <script type="text/javascript" src="script.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXT sjBbfaDjzALeQsN6M" crossorigin="anonymous"> 
    </body> 
</html> 

답변

2

은은 buttonClicked 변수에 여분의 공간이 될 것 같다 :

여기 내 코드입니다.

당신은 트림을 사용하여 조건이 작동합니다

buttonClicked = this.innerText.trim(); 
if (buttonClicked == triviaAnswer) { 

} 

+0

빠른 응답 감사합니다. 당신은 내가 얼마나 많은 시간을 보냈는지 알지 못한다. 하나의 오타에 대한 나의 코드를 조사하고 검토한다 ... 고맙다 !!! 투표를 할 수없는 범죄입니다 ... –

+1

OP는 조건부로 다듬어 진 문자열을 평가하는 대신 원래 변수를 업데이트해야한다고 생각합니다. 그렇지 않으면 매번이 작업을 수행하는 것을 기억할뿐만 아니라 모든 조건문에서 trim() 작업을 수행해야합니다. 불필요한 것 같습니다. –

+0

@Luke Stoward 맞습니다. 나는 편집했다. – RogerC

2

과 같이 두 값을 비교하는 시도 @Luke Stoward 주석 후 편집 :

if (buttonClicked.trim() == triviaAnswer.trim()) {..... 

을 때때로 공백 어딘가에있다 마지막에 Javascripts trim() 함수에 의해 제거됩니다.

+0

답변 해 주셔서 감사합니다. 나는 전혀 몰랐다! 이것은 그런 삶의 맛이다! 다시 한번, 나는 투표 할 수없는 범죄입니다! –

1

buttonClicked = this.innerText;으로 전화를 걸면 실제로 검색되는 값의 끝에 공백 문자가 표시되는 것 같습니다. 당신은이 방법을 보여줍니다이 당신은 내가 (코드 포함)이 바이올린을 만든 그래서

buttonClicked = buttonClicked.trim();

같은 공백 문자를 트림합니다 해결하려면 console.log(buttonClicked.length);

와 변수의 길이를 기록하여 확인할 수 있습니다 수정 및 작업 프로그램 : https://jsfiddle.net/fu3szacb/2/

사이드 노트 : 내가 자바 스크립트에서 전역 변수를 선언 피할 것,이 나쁜 연습과 혼란과 고통의 세계로 이어질 수 있습니다. 언어를 배울 때 이것을 피하는 것이 좋습니다.

전역 변수에 대한 컨텍스트를 제공하는 유용한 링크와이를 피해야하는 이유. 모두가 말했듯이 https://www.w3schools.com/js/js_scope.asp

0

,이 공백에 대해하고 트리밍하지 당신은 단지에 의해

buttonClicked = buttonClicked.trim(); 

시도 할 수 있었다하지만 자바 스크립트에서 문자열을 비교할에 올 때 가지고 추가 할 수 있습니다 (많은 소스가 있습니다) 비교 및 두 변수 모두에서 toLowerCase() 또는 toUpperCase()를 사용하는 것과 비교할 때 대개 trim() 및 조심해야합니다.

또한이 경우 정확한 문자열을 반환하기 때문에 문자열 비교에만 의존하지 않고 많은 오타 오류을 만들 수 있습니다. 제가 당신이라면 매번 대답으로 배열을 사용하기 때문에 번호를 검색하고 비교하면됩니다. 그러면 더 안전하고 쉽습니다.

정답의 위치/숫자 인덱스를 각 answer 변수에 저장할 수 있으며 HTML에서 숫자를 캡처 할 때 jQuery를 사용하고 있음을 알 수 있습니다.당신은 속성

numberAnswer="2" 

으로 모든 옵션 태그에 각 옵션의 수를 숨기고 단지

if ($(this).parent().attr('id') === "optionsContainer") { 

너무 비교가

이되는 선 아래

clickedNumberAnswer = $(this).attr('numberAnswer') 

그것을 얻을 수 있습니다

if(clickedNumberAnswer == triviaAnswer) 

공백에 문제가있는 것은 매우 이상한 일이며 대소 문자를 구분하는 것은 불가능합니다. 이제 triviaAnswer에 숫자가 포함되어야하고, 내 기억이 충분하다면 Javascript는 "2"== 2를 비교할 때 자동으로 변환되므로 더 좋습니다.