简体   繁体   English

JavaScript 代码不适用于特定条件

[英]JavaScript code doesn't work with a certain condition

I'm building a website with math games in which you can earn points.我正在建立一个包含数学游戏的网站,您可以在其中赚取积分。 The scores are being calculated after finishing a game.比赛结束后计算分数。 So score1 for game1 starts at 0 but if you do it correctly, you'll get 10 point, same goes for the other games (game2 = score2, game3 = score3 etc.)所以 game1 的 score1 从 0 开始,但如果你做得正确,你会得到 10 分,其他游戏也是如此(game2 = score2,game3 = score3 等)

To calculate the total score I use:要计算我使用的总分:

var totalscore = parseInt(score1) + parseInt(score2) + parseInt(score3) ... and so on

I've got a function to check the total score every once in a while:我有一个功能可以每隔一段时间检查一次总分:

function totaalscoreshow() {
    var totaalscore = parseInt(score1) + parseInt(score2) + parseInt(score3) + 
    parseInt(staat.scoreM1) + parseInt(M_score2) + parseInt(M_score3) + 
    parseInt(H_staat.scoreH1) + parseInt(H2_staat.scoreH2) + parseInt(verlies_winst);

    document.getElementById("totaalscore").innerText = totaalscore;
    document.getElementById("totaalBet").innerText = totaalscore;
}

totaalscoreshow();
setInterval(totaalscoreshow, 100);'

The total score is also defined as a global variable.总分也被定义为一个全局变量。

This all works fine.这一切都很好。 But I'm trying to put the total score in a condition.但我试图把总分放在一个条件下。 I tried it in multiple ways.我尝试了多种方式。 Among which:在这之中:

function CheckInzet() {
        setInterval(totaalscoreshow, 100)
        if (totaalscore < parseInt(inzet.value) || totaalscore <= 0) {
            inzet_leeg.innerText = "Je hebt niet genoeg punten om in te zetten";
            return;
        } else {
            inzetCorrect = true;
        }
    }
setInterval(CheckInzet, 11);

if (inzetCorrect == true) {
    ... more code ...
}
... more code ...

also this way:也是这样:

totaalscoreshow();
    if (totaalscore < parseInt(inzet.value) || totaalscore <= 0){
        inzet_leeg.innerText = "Je hebt niet genoeg punten om in te zetten";
        return;
    } else if (inzet.value == "0" || inzet.value == 0) {
        inzet_leeg.innerText = "Je moet punten inzetten."
        return;
    } else if (inzet.value == "") {
        inzet_leeg.innerText = "Zet eerst een aantal punten in.";
        return;
    } else if (newClicked == true && inzet.value !== "") {
        inzet_leeg.innerText = "Start eerst een nieuwe ronde";
        return;
    } else if (clicked == true) {
        inzet_leeg.innertext = "Maak eerst deze ronde af";
        return;
    } 

... more code ...

I tried playing with it in more ways, but the problems keeps existing.我尝试以更多方式使用它,但问题仍然存在。

When the total score is indeed less than or equal to 0, or less than inzet.value , it does what it should do.当总分确实小于或等于 0 或小于inzet.value时,它​​会做它应该做的事情。

But then when the total score is greater than 0 or greater than inzet.value , it still acts like it isn't.但是当总分大于 0 或大于inzet.value时,它​​仍然表现得好像不是。 All the other code works when I leave the condition of totaalscore out.当我将总分数的条件totaalscore在外时,所有其他代码都可以工作。 But I need it to work with this condition.但我需要它来处理这种情况。

I didn't entirely understand your problem but there are few things you can improve in your code:我没有完全理解您的问题,但您的代码中可以改进的地方很少:

Instead of doing而不是做

var totalscore = parseInt(score1) + parseInt(score2) + parseInt(score3) ...

you should try storing these variables as int so you dont have to convert them each time, also consider storing them together (in an array for exemple) so that you can add them faster using:您应该尝试将这些变量存储为 int 这样您就不必每次都转换它们,还可以考虑将它们存储在一起(例如在数组中),以便您可以使用以下方法更快地添加它们:

scores=[100,0,31,28] // array of score1, score2, etc...
var totaalscore=scores.reduce((a, b) => a + b);

If you can't store your scores as int you can try this before adding them together:如果您无法将分数存储为 int,则可以在将它们相加之前尝试此操作:

var totaalscore=scores.map((a)=>parseInt(a))

Keep also in mind that in JS any number different from 0 considered as true.还要记住,在 JS 中,任何不同于 0 的数字都被认为是真实的。

true==1 //true
true==5 //true
true== -1 // true
true== 0 //false

if (inzetCorrect == true) {}
//is the same as 
if (inzetCorrect){}

var condition=(5>1) //value "true" is stored in "condition"
if(condition){
    //it will do something
}

Your last piece of code could be more optimized if you use the switch statement, it works faster: https://www.w3schools.com/js/js_switch.asp如果您使用 switch 语句,您的最后一段代码可能会更优化,它运行得更快: https ://www.w3schools.com/js/js_switch.asp

Glad you've already solved your problem :) I recommend you drawing a scheme of your program so that you don't get confused the next time很高兴你已经解决了你的问题 :) 我建议你画一个你的程序的方案,这样你下次就不会感到困惑了

I think you need to optimze your game logic , for example the OPP of js can help you to make it dynamicly我认为你需要优化你的游戏逻辑,例如js的OPP可以帮助你使其动态化

This is a simple js class that can help you to make your code more clean这是一个简单的js类,可以帮助你让你的代码更干净

For example you can remove the interval of calcolting total by manging change event例如,您可以通过管理更改事件来删除计算总数的间隔

 class ScoreManager { plyers = { 'player_1':{ scores:{ game_one:10 }, totalScore:0 } } _onScoreChange = ()=>{} constructor() { } onScoreChange(cb){ this._onScoreChange = cb } addPlayer(plyerName){ if(this.plyers[plyerName]) throw new Error("Player already exists!") this.plyers[plyerName] = { scores:{} } } addScoreForPlyer(plyerName,gameName,score){ if(!this.plyers[plyerName]) throw new Error("Player dosn't exists!"); this.plyers[plyerName].scores[gameName] = score this.calcolateScore(plyerName) } removeScoreForPlyer(plyerName,gameName){ if(!this.plyers[plyerName]) throw new Error("Player dosn't exists!"); delete this.plyers[plyerName].scores[gameName] this.calcolateScore(plyerName) } removePlyer(plyerName){ delete this.plyers[plyerName] } calcolateScore(plyerName){ let totalScore = 0 Object.keys(this.plyers[plyerName].scores).forEach(r=>{ totalScore+=this.plyers[plyerName].scores[r] }) this.plyers[plyerName].totalScore = totalScore this._onScoreChange(plyerName,totalScore,this.plyers) return totalScore } } //Home to use it const scoreManger = new ScoreManager() scoreManger.onScoreChange((plyerName,totalScore,plyers)=>{ console.log(`The plyer ${plyerName} has score ${totalScore}`) console.log(`totalPlyerObject`,plyers) }) scoreManger.addPlayer("max"); scoreManger.addScoreForPlyer("max",'step_one',10)

Turned out that there was indeed something wrong with the count of totalscore in this specific function.原来这个特定函数的总分计数确实有问题。 But the totalscore was being updated as the innertext of a p-element.但是总分被更新为 p 元素的内部文本。 I fixed it by just reading the number in innertext and checking that value in the condition instead of the totalscore.我通过读取内部文本中的数字并检查条件中的值而不是总分来修复它。 Instead of fixing the problem I found a other solution.我没有解决问题,而是找到了其他解决方案。 I know as a coder you should fix it, but I'm running out of time for my assignment and now this works, so I'm happy :D我知道作为一名编码员你应该修复它,但我的任务已经没有时间了,现在它可以工作了,所以我很高兴:D

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

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