Trying to update an array after an event under certain conditions

放肆的年华 提交于 2019-12-12 02:16:05

问题


I've been having problems with logic and i need help addressing this issue. I come up with these types of problems all the times and i cant seem to set the variables at the right places to get the right logic to occur. basically what i want in the code is that if someone inputs the wrong (addition) answer and clicks go you should push to an array the questions and the answer. so i could get a list of the questions and answers in the array after the user finishes answering a bunch of questions. if i just push the question every time on the click i will get repeats in the array. so i need a condition, something like if the last one was wrong and it is not in the array only put it in the array once. the user could keep on attempting to answer until he gets it right.

I tried to set a wrong = 0 in global scope and in the if else statement increase the counter++ and check to see if the counter is less than 2 if it is less than 2 that means the counter could be 1 which which also means that a wrong answer was attempted so that's when I push the info to the array than i reset it to 0 but thats not good it looks like wrong will always be 1

  $(document).ready( function(){

        var wrong = 0
        wrongQs = []
        clicked = false

         number1 = ~~(Math.random() * 10);
         number2 = ~~(Math.random() * 10);
        $(".numbers").children().remove()
        $(".numbers").html("<div>" + number1 +"</div><div>" + number2 + "</div>")

        $("button.go").on('click' , function(e){
            clicked = true
            console.log($(".input").val()," " ,(number1 + number2))
            //alert(+$(".input").val())
            if(+$(".input").val() == (number1 + number2)){
                 number1 = ~~(Math.random() * 10);
                 number2 = ~~(Math.random() * 10);
                $(".numbers").children().remove()
                $(".numbers").html("<div>" + number1 +"</div><div>" + number2 + "</div>")
            }else{
                wrong++
                if( wrong < 2){
                    wrongQs.push([number1, number2, number1+ number2])
                    console.log("WrongQs Array " , wrongQs)
                    wrong = 0
                }

            }
        })
    });

html:

    <div class="numbers"></div>
<input class = "input"> <button class="go">Go</button>

and how can i become a better logical programmer? I've been at this for almost 2 yrs

来源:https://stackoverflow.com/questions/31260171/trying-to-update-an-array-after-an-event-under-certain-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!