检查变量中的值并显示一个或多个最高值

发布于 2025-01-10 16:25:53 字数 1010 浏览 0 评论 0原文

我正在学习 Javascript,并且正在尝试为音乐家建立一个带有工具的网站。 这是我无法弄清楚如何使用正常条件、比较等来实现的事情。

假设我有 5 个变量:

a = 0;
b = 0;
c = 0;
d = 0;
e = 0;

现在使用一些复选框,变量现在更新为:

a = 0;
b = 3;
c = 1;
d = 3;
e = 0;

所以我想要变量 bd 成为优先变量,因为它们都是具有最高值 (3) 的变量。 或者,如果只有 1 个变量获得最高值,则该单个变量将具有优先级,例如:

a = 0;
b = 7;
c = 1;
d = 3;
e = 0;

在本例中,变量 b 将具有优先级,因为它是最高的数字。

实现这一目标的最佳方法是什么? 基本上我想比较所有值并首先检查最高值是多少? 然后,具有该值的一个或多个变量将被分配例如不同的名称或值。例如,如果每个变量都是音符名称(C、D#、F、G、Ab),那么我会在其名称中添加 + 号(例如 D#+ 和 G+)。 老实说,这部分与前端的最终结果无关。我只是想了解这背后有什么样的逻辑以及如何实现?

谢谢你! :)

编辑: 所以我想到的一种方法是: 首先,收集所有变量并从最高值到最低值对它们进行排序:

b = 3;
d = 3;
c = 1;
a = 0;
e = 0;

首先,将 b 设置为 TRUE。 然后将 d 与 b 进行比较。如果是相同的数字,则将其设置为 TRUE,否则将其设置为 FALSE。对 c 执行相同操作,并将其与 B 进行比较。将 a 与 b 进行比较,e 与 B 进行比较。

最终我得到顶部的所有 TRUE 变量,而所有其他变量均为 FALSE。

这是一个好方法吗?还有其他更简单的选择吗? 这适用于 5 个变量,但如果我有 100 个变量呢?

I'm learning Javascript and I'm trying to build a website with a tool for musicians.
Here's something I can't figure out how to achieve using normal conditions, comparisons, etc.

Let's say I have 5 variables:

a = 0;
b = 0;
c = 0;
d = 0;
e = 0;

Now using some checkboxes, the variables now update to:

a = 0;
b = 3;
c = 1;
d = 3;
e = 0;

So I want variables b and d to become the prioritized variables, because they are both the variables with the highest value (3).
Or if only 1 variable would get the highest value, that single variable would be priority, for example:

a = 0;
b = 7;
c = 1;
d = 3;
e = 0;

In this case variable b would become prioritized, because it's the highest number.

What's the best way to accomplish this?
Basically I want to compare all values and first check what's the highest value?
Then, the variable or variables with that value would be assigned for example a different name or value. For example if each variable was a musical note name (C, D#, F, G, Ab), then I would add a + sign to their name (e.g. D#+ and G+).
This part, what the end result will be on the front end, is not that relevant, to be honest. I just want to understand what kind of logic goes behind this and how can that be achieved?

Thank you! :)

EDIT:
So one approach I was thinking of was:
First, gather all the variables and sort them from highest value to lowest:

b = 3;
d = 3;
c = 1;
a = 0;
e = 0;

First, set b to TRUE.
Then compare d with b. If it's the same number, set it to TRUE, else set it to FALSE. Do the same for c and compare it to B. Compare a with b, e with B.

I end up with all the TRUE variables at the top and all the other ones as FALSE.

Is this a good approach? Is there another easier alternative?
This works with 5 variables, but what about if I had 100?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文