简体   繁体   English

Javascript if / if else / else无法正常工作

[英]Javascript if/if else/else not working

So I have this javascript, but it's not working. 所以我有这个JavaScript,但无法正常运作。

var verbs = [ ["ambulo", "ambulare", "ambulavi", "ambulatus"], ["impedio", "impedire", "impedivi", "impeditus"] ]
var verbNumber = verbs.length - 1;

function randomIntFromInterval(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}

/* Picks a verb */
var thisVerb = verbs[randomIntFromInterval(0, verbNumber)];

/* Checks the conjugation */
var second = thisVerb[1];
var secondLength = second.length;
var start = secondLength - 3;
var secondEnding = second.substring(start, secondLength);
var conjugationNumber = 0;

if (secondEnding === "are") {
conjugationNumber = 1;
} else if (secondEnding === "ēre") {
conjugationNumber = 2;
} else if (secondEnding === "ere") {
conjugationNumber = 3;
} else if (secondEnding === "ire") {
conjugationNumber = 4;
} else {
console.log("error");
};      

/* Randomly picks how to conjugate */
var tense = randomIntFromInterval(1, 6);
var person = randomIntFromInterval(1, 3);
var number = randomIntFromInterval(1, 2);
var voice = randomIntFromInterval(1, 2);

/* Conjugates */
var thisDictEntry = 0;

if ((conjugationNumber === 1 || 2) && (tense === 1 || 2 || 3)) {
thisDictEntry = 2;
} else if ((conjugationNumber === 3 || 4) && (tense === 1 || 2 || 3)) {
thisDictEntry = 1;
} else if ((tense === 4 || 5 || 6) && (voice === 1)) {
thisDictEntry = 3;
} else if ((conjugationNumber === 3 || 4) && (voice === 2)) {
thisDictEntry = 4;
} else {
console.log("Error");
};

What should happen is a random verb (array within an array) is picked, then becomes randomly conjugated. 应该发生的是,选择一个随机动词(数组中的数组),然后将其随机共轭。 All the code works up until the if/else if/else statements under the /* Conjugates */. 所有代码都可以处理,直到/ *共轭* /下的if / else if / else语句为止。 That, for some reason, always sets thisDictEntry to 2. 由于某种原因,始终将thisDictEntry设置为2。

Why? 为什么?

The first condition: 第一个条件:

((conjugationNumber === 1 || 2) && (tense === 1 || 2 || 3)) 

should be: 应该:

((conjugationNumber === 1 || conjugationNumber === 2) && (tense === 1 || tense === 2 || tense === 3)) 

the problem with your version is that javascript does the following: 您的版本存在的问题是javascript执行以下操作:

conjugationNumber === 1 // this results in true/false
or
2 // this is always true 

because js evaluates it as truthy . 因为js认为它是true

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

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