gpt4 book ai didi

javascript - 从数组中获取最大的 3 个数字?

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

下面的代码返回数组中的最大数字。我试图弄清楚如何从数组中获取前 3 个数字,但一直无法弄清楚。

我还想弄清楚如何列出相应的职位及其分数。目前,带有“Your Highest Score was”的 H1 仅显示数字,不会通过作业(或最高数字的 var 名称)。

关于如何实现这一目标有什么想法吗?

谢谢!

HTML:

<div>
<h3> Job 95- <span id="score95"> </span> </h3>
<h3> Job 96- <span id="score96"> </span> </h3>
<h3> Job 97- <span id="score97"> </span> </h3>
<h3> Job 98- <span id="score98"> </span> </h3>
<h3> Job 99- <span id="score99"> </span> </h3>
<h3> Job 100- <span id="score100"> </span> </h3>
<h1> Your highest score was: <span id="highest"></span></h1>
</div>

JS

var job95 = 100;
var job96 = 100;
var job97 = 100;
var job98 = 100;
var job99 = 100;
var job100 = 100;

$( "#no15" ).click(function() {
console.log('clicked15')
job95 += 10;
job96 += 20;
job97 += 30;
job98 += 40;
job99 += 50;
job100 += 60;
$('#score95').html(job95);
$('#score96').html(job96);
$('#score97').html(job97);
$('#score98').html(job98);
$('#score99').html(job99);
$('#score100').html(job100);

var numArray = [job95,job96, job97, job98, job99,job100]
$('#highest').html(Math.max.apply(Math,numArray));
});

最佳答案

从低到高排序,然后切片。示例:

var arr = [1, 3, 2, 1, 5, 6, 3];
//Sort the array from lowest to highest
//Thanks to Charlietfl, I forgot to sort it numerically
arr.sort(function(a, b) {
return a - b;
});
//Get the highest 3
var top3Arr = arr.slice(-3);
console.log(top3Arr)


//This is an array, so if you want each number individually just access the array

var highest = top3Arr[2];
var secondHighest = top3Arr[1];
var thirdHighest = top3Arr[0];

关于javascript - 从数组中获取最大的 3 个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275401/

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