计算数组中的最大值/最小值
内置函数Math.max()和Math.min()可以分别找出参数中的最大值和最小值。
1 | Math.max(1, 2, 3, 4); // 4 |
这些函数对于数字组成的数组是不能用的。但是,这有一些类似地方法。
Function.prototype.apply()
让你可以使用提供的this
与参数组成的_数组(array)_来调用函数。
1 | var numbers = [1, 2, 3, 4]; |
给apply()
第二个参数传递numbers
数组,等于使用数组中的所有值作为函数的参数。
一个更简单的,基于ES2015的方法来实现此功能,是使用展开运算符.
1 | var numbers = [1, 2, 3, 4]; |
此运算符使数组中的值在函数调用的位置展开。
原文作者: anhr
原文链接: http://yoursite.com/2019/11/04/javascript/2016-02-14-calculate-the-max-min-value-from-an-array/
版权声明: 转载请注明出处(必须保留原文作者署名原文链接)