通过IF语句添加分数

时间:2017-03-16 13:12:25

标签: javascript if-statement

我正在尝试构建一个用户必须对某些单词进行排名的脚本。我试图将得分保持在最新状态,但它一直出错。当我测试代码并且我回答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);

3 个答案:

答案 0 :(得分: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':
    // .......
}

答案 1 :(得分:0)

您可以使用switch并将字符设置为小写,以避免对Aa进行双重检查



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');

switch(q1[0].toLowerCase()){
  case 'a':
    orientaal+=3;
    break;
  case 'b':
    bloemig+=3;
    break;
  case 'c':
    houtig+=3;
    break;
  case 'd':
    citrus+=3;
    break;
}

console.log('orientaal = ' + orientaal);
console.log('houtig = ' + houtig);
console.log('bloemig = ' + bloemig);
console.log('aromatisch = ' + aromatisch);
console.log('chypre = ' + chypre);
console.log('citrus = ' + citrus);




答案 2 :(得分:0)

如果排名始终相同,即最高答案将获得+3,第二个+2,第三个+1和最后一个+0到其关联的actegory,您可以通过使用一些来简化整个计算数据结构。 基本上,您只需将每个可能的答案与一个类别相关联,然后将所有分数统计在一起。

最大的好处是您可以在不更改其余代码的情况下添加问题和类别。否则,你必须为你添加的每个问题再次编写整个if / else逻辑,如果添加一个类别,则编辑你已经拥有的所有if / else。

在这里展示原则。应该扩展代码,更好地检查用户输入。而且obv使用你自己的问题。等

    // Array with all used categories
var categories = [
        'orientaal',
        'houtig',
        'bloemig',
        'aromatisch',
        'chypre',
        'citrus'
    ],
    // Array containing all the questions and the category of each answer
    questions = [
        {
            'text' : 'Welk element spreekt jou het meest aan? Zet de letters van hoog naar laag (Bijv. DBAC).',
            'answers' : {
                'A' : {
                    'val' : 'Vuur',
                    'category' : 'orientaal'
                },
                'B' : {
                    'val' : 'Lucht',
                    'category' : 'bloemig'
                },
                'C' : {
                    'val' : 'Aarde',
                    'category' : 'houtig'
                },
                'D' : {
                    'val' : 'Water',
                    'category' : 'citrus'
                }
            }
        }, {
            'text' : 'Welk dier spreekt jou het meeste aan?',
            'answers' : {
                'A' : {
                    'val' : 'Draak',
                    'category' : 'orientaal'
                },
                'B' : {
                    'val' : 'Arend',
                    'category' : 'aromatisch'
                },
                'C' : {
                    'val' : 'Wolf',
                    'category' : 'houtig'
                },
                'D' : {
                    'val' : 'Slang',
                    'category' : 'chypre'
                }
            }
        }, {
            'text' : 'Welke locatie spreekt je het meeste aan?',
            'answers' : {               
                'A' : {
                    'val' : 'Dennenbos',
                    'category' : 'houtig'
                },
                'B' : {
                    'val' : 'Steppe',
                    'category' : 'orientaal'
                },
                'C' : {
                    'val' : 'Oerwoud',
                    'category' : 'citrus'
                },
                'D' : {
                    'val' : 'Heide',
                    'category' : 'bloemig'
                }
            }
        }
    ],
    // Array to save the answers of the user.
    userAnswers = [],
    // Var to create the results.
    scoreList;

// Let's 'fake' an interface that asks the questions. Replace this with your own form and functions that push the answers to the userAnswers array.
questions.forEach(function( questionObj, index ) {
        // Create the text for the possible answers from our questionObject.
    var answerText = Object.keys(questionObj.answers).map(function( letter ) {
            // We just return the letter, plus a dot, plus the value corresponding with that letter.
            return letter + '.: ' + questionObj.answers[ letter ].val;
        }).join(', '),
        // Ask the question, using the text inside our questionObj.
        prompt = window.prompt('Vraag ' + (index + 1) + ': ' + questionObj.text + ' ' + answerText, '');
    // Check if a 'valid' answer was entered. This should be expanded to also check that the input consists of some combination of ABCD
    // if (prompt && prompt.length === 4) userAnswers.push( prompt );
    // else alert('Gelieve alle 4 de letters in volgorde te zetten');
    // But for now we'll just accept any answer for testing purposes.
    userAnswers.push( prompt );
});
// Now let's check the score of the answers. We can reduce the users' answers into one value object that we can create by reducing our categories into a 'score list': A plain object with the category as the key adn the count as the value.
scoreList = userAnswers.reduce(function( scoreList, answer, index ) {
    // Since our answers are in the same order as our questions, we can just use the idnex to get the question associated with this answer.
    var questionObj = questions[ index ],
        // By splitting the answer, we get an array containing the 4 individual letters.
        answerLetters = answer.split('');
    // For each letter that is part of the answer, add the correct value to our score list.
    answerLetters.forEach(function( letter, index ) {
        // The answered letter gives us the correct category
        var category = questionObj.answers[ letter ].category;
        // We can just use a static array to transform the index into the score: index 0 = score 3, i1 = s2, i2 = s1, i3 = s0
        scoreList[ category ] += [ 3, 2, 1, 0 ][ index ];
    });
    return scoreList;
}, categories.reduce(function( scoreList, category ) {
    scoreList[ category ] = 0;
    return scoreList;
}, {}));
// Report the results
alert( JSON.stringify( scoreList ) );