gpt4 book ai didi

javascript - 减少 Javascript 中的 if 语句

转载 作者:行者123 更新时间:2023-11-27 23:48:47 24 4
gpt4 key购买 nike

我想跟踪数据中各种值的计数。目前,我为每个变量使用一个计数器变量,并使用许多 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

}
});

最佳答案

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

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

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)];
}
});

关于javascript - 减少 Javascript 中的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com