Javascript如果/ if else / else不起作用

时间:2015-05-28 16:32:57

标签: javascript if-statement

所以我有这个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");
};

应该发生的是随机动词(数组中的数组)被拾取,然后随机共轭。所有代码一直运行,直到/ * Conjugates * /下的if / else if / else语句。由于某种原因,它始终将thisDictEntry设置为2。

为什么?

1 个答案:

答案 0 :(得分:3)

第一个条件:

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

应该是:

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

您的版本存在的问题是javascript会执行以下操作:

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

因为js将其评估为truthy