思路:首先定义一个随机数的函数,然后将数组里面的每一项都调用此函数,最后排序。
具体代码如下:
<script>
function fn() {
let arr = [];
for (let i = 0; i < 10; i++) {
arr.push(Math.floor(Math.random() * 9) + 1)
}
arr.sort((a, b) => b - a);
let max = Array.from(new Set(arr))
document.write(arr + "该数组中第二大的数为:" + max[1])
}
fn()
</script>
首先往数组中添加10个随机数,然后用sort进行排序,对排序之后的数组进行去重。关于去重的解释,我的博客里面也有详细的解释。