减少Javascript中的if语句
我希望跟踪数据中各种值的计数。目前,我正在为每个变量使用一个计数器变量,并使用许多if语句来查找最后的最大值 我可以减少代码中if语句的数量吗 这是我的代码:减少Javascript中的if语句,javascript,Javascript,我希望跟踪数据中各种值的计数。目前,我正在为每个变量使用一个计数器变量,并使用许多if语句来查找最后的最大值 我可以减少代码中if语句的数量吗 这是我的代码: myApp.service('faceReaderDataService', function () { var dominantExpression = "Neutral"; this.analyzeFaceReaderData = function (emotionArray) { var neutra
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
}
});
myApp.service('faceReaderDataService',函数(){
var-dominantExpression=“中立”;
this.analyzeFaceReaderData=函数(emotionArray){
var中性_计数器=0;
var\u计数器=0;
var\u计数器=0;
//其他情绪如悲伤、厌恶将不予考虑
对于(var i=0;i快乐计数器和中性计数器>愤怒计数器){
显性表达=“中性”;
}
否则如果(高兴的计数器>中立的计数器&高兴的计数器>愤怒的计数器){
支配性表达=“快乐”;
}
否则如果(愤怒的计数器>中立的计数器&愤怒的计数器>快乐的计数器|愤怒的计数器==中立的计数器){
支配性表达=“愤怒”;
}
....//如果两个相等,则进行比较
}
});
您可以使用两个数组。一个掌握着情感的弦,另一个掌握着计数。使用计数数组进行计数。然后在count数组中找到max值,并使用字符串数组中相应的索引来查找您的值
如果这是默认值,你也不需要检查中性情绪
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)];
}
});
myApp.service('faceReaderDataService',函数(){
var-dominantExpression=“中立”;
this.analyzeFaceReaderData=函数(emotionArray){
变量情感=[“中立”、“快乐”、“愤怒”];
变量emotionCounts=[0,0,0]
对于(var i=0;i