在 JavaScript 数组中查找最大值/最小值
本教程将讨论如何使用 JavaScript 中的 Math.min()
和 Math.max()
函数查找数组的最小值和最大值。
要找到给定数组中存在的最小值,我们可以使用 JavaScript 中的 Math.min()
函数。此函数返回给定数组中存在的最小值。例如,让我们用一些随机值定义一个数组,并使用 Math.min()
函数找到它的最小值,然后使用 console.log()
函数将其显示在控制台上。请参考下面的代码。
var myArray = [1, 5, 6, 2, 3];
var m = Math.min(...myArray);
console.log(m)
输出:
1
正如你在输出中看到的,数组的最小值由 Math.min()
函数返回。某些浏览器可能不支持上述方法,因此你可以使用 apply()
函数和 Math.min()
函数从给定数组中获取最小值。例如,请参考下面的代码。
var myArray = [1, 5, 6, 2, 3];
var m = Math.min.apply(null, myArray);
console.log(m)
输出:
1
apply()
函数调用具有给定 this
值和上述代码中给定数组的函数。如果你不想使用任何预定义的函数,你可以使用 JavaScript 中的循环创建自己的函数。例如,让我们创建一个函数来查找数组的最小值。请参考下面的代码。
function MyMin(myarr){
var al = myarr.length;
minimum = myarr[al-1];
while (al--){
if(myarr[al] < minimum){
minimum = myarr[al]
}
}
return minimum;
};
var myArray = [1, 5, 6, 2, 3];
var m = MyMin(myArray);
console.log(m)
输出:
1
在上面的代码中,我们将给定数组的最后一个元素保存到变量 minimum
,并将其与前一个元素进行比较。如果元素小于变量 minimum
,我们将这个元素存储在变量 minimum
中。如果没有,我们将移动到下一个元素。我们将重复这个过程,直到我们到达索引 0。循环之后,我们将返回变量 minimum
。
要找到给定数组中存在的最大值,我们可以使用 JavaScript 中的 Math.max()
函数。此函数返回给定数组中存在的最大值。请参考下面的代码。
var myArray = [1, 5, 6, 2, 3];
var m = Math.max(...myArray);
console.log(m)
输出:
6
你还可以使用 apply()
函数和 Math.max()
函数从给定数组中获取最大值。例如,请参考下面的代码。
var myArray = [1, 5, 6, 2, 3];
var m = Math.max.apply(null, myArray);
console.log(m)
输出:
6
让我们创建一个函数来查找数组的最大值。请参考下面的代码。
function MyMax(myarr){
var al = myarr.length;
maximum = myarr[al-1];
while (al--){
if(myarr[al] > maximum){
maximum = myarr[al]
}
}
return maximum;
};
var myArray = [1, 5, 6, 2, 3];
var m = MyMax(myArray);
console.log(m)
输出:
6
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。