gpt4 book ai didi

javascript - Javascript 中使用菊花链三元处理数组和平均值的解决方案?

转载 作者:行者123 更新时间:2023-12-02 23:01:38 25 4
gpt4 key购买 nike

我试图更好地理解 JavaScript 中的数组和函数,但我发现很难对数组值进行排序并返回其等效容器

由于代码较少,我喜欢简单的三元链,而不是 if/else 条件和 switch case 语句,但我想取消对数组中平均值计算的编码,并且如果射手具有最高的平均值或其他内容,则可能返回射手的姓名。如果有我遗漏的数学公式,我会很感激。谢谢。

var Steph, RayA, LarryB, AvSteph, AvRay, AvLarry, Ax;

Steph = [286, 402, 324];
RayA = [116, 103, 123];
LarryB = [90, 82, 80];

AvSteph = (Steph[0] + Steph[1] + Steph[2]) / Steph.length;
AvRay = (RayA[0] + RayA[1] + RayA[2]) / RayA.length;
AvLarry = (LarryB[0] + LarryB[1] + LarryB[2]) / LarryB.length;
Ax = [AvSteph, AvRay, AvLarry];

console.log(' Steph\'s average is ' + AvSteph, '\n Ray\'s average is ' + AvRay, '\n Larry\'s average is ' + AvLarry);

Ax[0] > Ax[1] && Ax[0] > Ax[2] ? console.log('Stephen Curry is the 3-point Hero') :
Ax[1] > Ax[0] && Ax[1] > Ax[2] ? console.log('Ray Allen is the 3-point Hero') :
Ax[2] > Ax[0] && Ax[2] > Ax[1] ? console.log('Larry Bird is the 3-point Hero') :
Ax[0] == Ax[1] && Ax[0] == Ax[2] ? console.log('It is a three tie win!') :
Ax[0] == Ax[1] && Ax[0] > Ax[2] ? console.log('It\'s a tie! Stephen Curry and Ray Allen are the 3-point Heroes') :
Ax[0] > Ax[1] && Ax[0] == Ax[2] ? console.log('It\'s a tie! Stephen Curry and Larry Bird are the 3-point Heroes') :
Ax[0] < Ax[1] && Ax[1] == Ax[2] ? console.log('It\'s a tie! Ray Allen and Larry Bird are the 3-point Heros') :
console.log('I\'m not sure who the 3-point Hero is :( ');

这将返回:

Stephen's average is 337.33 
Ray's average is 114
Larry's average is 84
Stephen Curry is the 3-point Hero

正在寻找更少且最佳的代码...感谢您的建议

最佳答案

首先,您应该定义一个函数来对任意长度的任意数组求平均值:

function getAverage(array) {
return array.reduce(function(a, b) { return a + b; }) / array.length;
}

然后创建一个包含名称和平均值的数组:

var averagesByName = [
{name: 'Stephen Curry', average: getAverage(Steph)},
{name: 'Ray Allen', average: getAverage(RayA)},
{name: 'Larry Bird', average: getAverage(LarryB)}
];

然后对这个数组进行排序:

// Sort highest first, lowest last
averagesByName.sort(function(a, b) { return b.average - a.average })

您仍然需要对关系进行特殊检查,但不必逐个进行。

关于javascript - Javascript 中使用菊花链三元处理数组和平均值的解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57758550/

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