通过IF语句添加分数

Rob*_*pen 2 javascript if-statement

我正在尝试构建一个用户必须对某些单词进行排名的脚本.我试图保持得分uo到目前为止但它一直出错.当我测试代码并且我回答AB时,orientaal的结果等于5.结果应该是orientaal = 3和bloemig = 2.这是我做的代码(我不是很有经验):

var orientaal = 0;
var houtig = 0;
var bloemig = 0;
var aromatisch = 0;
var chypre = 0;
var citrus = 0;

var q1 = prompt('Welk element spreekt jou het meest aan? Zet de letters van hoog naar laag (Bijv. DBAC). \n A. Vuur \n B. Lucht \n C. Aarde \n D. Water')

if(q1.charAt(0) == 'A' || 'a') {
  orientaal = orientaal + 3;
}else if(q1.charAt(0) == 'B' || 'b') {
  bloemig = bloemig + 3;
}else if(q1.charAt(0) == 'C' || 'c') {
  houtig = houtig + 3;
}else if(q1.charAt(0) == 'D' || 'd') {
  citrus = citrus + 3;
}

if(q1.charAt(1) == 'A' || 'a') {
  orientaal = orientaal + 2;
}else if(q1.charAt(1) == 'B' || 'b') {
  bloemig = bloemig + 2;
}else if(q1.charAt(1) == 'C' || 'c') {
  houtig = houtig + 2;
}else if(q1.charAt(1) == 'D' || 'd') {
  citrus = citrus + 2;
}

console.log('orientaal = ' + orientaal);
console.log('houtig = ' + houtig);
console.log('bloemig = ' + bloemig);
console.log('aromatisch = ' + aromatisch);
console.log('chypre = ' + chypre);
console.log('citrus = ' + citrus);
Run Code Online (Sandbox Code Playgroud)

Nie*_*sol 8

if(q1.charAt(0) == 'A' || 'a')不会做你认为它做的事情.具体来说,这就是说

如果第一个字符q1'A',或者'a'是真实的

因为下半场总是正确的(除了空字符串之外所有的字符串都是真的),你总会得到一个通行证.

相反,请考虑使用switch如下:

switch(q1[0]) { // strings can be accessed as arrays of characters
  case 'A':
  case 'a':
    orientaal += 3;
    break;
  case 'B':
  case 'b':
    // .......
}
Run Code Online (Sandbox Code Playgroud)