减少Javascript中的if语句

时间:2015-10-02 07:26:59

标签: javascript

我想跟踪数据中各种值的计数。目前我正在为每个使用一个计数器变量,并使用许多if语句来查找最后的最大值。

我可以减少代码中if语句的数量吗?

这是我的代码:

myApp.service('faceReaderDataService', function () {
    var dominantExpression = "Neutral";
    this.analyzeFaceReaderData = function (emotionArray) {
        var neutral_counter = 0;
        var happy_counter = 0;
        var angry_counter = 0;
        //other emotions like Sad, Disgusted will not be considered
        for (var i = 0; i < emotionArray.length; i++) {
            var Emotion = emotionArray[i].data.FaceReader.Emotion ;
            if (Emotion == "Neutral"){
                neutral_counter += 1;
            }
            else if(Emotion == "Happy"){
                happy_counter += 1;
            }
            else if (Emotion == "Angry"){
                angry_counter += 1;
            }
            else {
                neutral_counter += 1;
            }    
        }

        if (neutral_counter > happy_counter && neutral_counter > angry_counter) {
            dominantExpression = "Neutral";
        }
        else if (happy_counter > neutral_counter && happy_counter > angry_counter) {
            dominantExpression = "Happy";
        }
        else if (angry_counter > neutral_counter && angry_counter > happy_counter | angry_counter == neutral_counter ){
            dominantExpression = "Angry";
        }
        .... //comparing if two are equals

    }
});

1 个答案:

答案 0 :(得分:1)

您可以使用两个数组。一个持有情感串,另一个持有计数。使用count数组计算。然后在count数组中找到最大值,并使用字符串数组中的相应索引来查找您的值。

如果这是默认情况,您也不需要检查中性情绪。

myApp.service('faceReaderDataService', function () {
    var dominantExpression = "Neutral";
    this.analyzeFaceReaderData = function (emotionArray) {

        var emotions = ["Neutral", "Happy", "Angry"];
        var emotionCounts = [0,0,0]

        for (var i = 0; i < emotionArray.length; i++) {
            var Emotion = emotionArray[i].data.FaceReader.Emotion ;

            if(Emotion == emotions[1]){
                emotionCounts[1] += 1;
            }
            else if (Emotion == emotions[2]){
                emotionCounts[2] += 1;
            }
            else {
                emotionCounts[0] += 1;
            }    
        }
        maxCount = Math.max(emotionCounts[0], emotionCounts[1], emotionCounts[2]):
        dominantExpression = emotions[emotionCounts.indexOf(maxCount)];
    }
});