javascript - 如何在javascript中获取数组中的最小元素?

标签 javascript

这是我尝试过的:

Math.min([1,2,3])

但只得到NaN...

最佳答案

使用应用:

Math.min.apply(null,[1,2,3]); //=> 1

From devguru :

Function.apply(thisArg[, argArray]) the apply method allows you to call a function and specify what the keyword this will refer to within the context of that function. The thisArg argument should be an object. Within the context of the function being called, this will refer to thisArg. The second argument to the apply method is an array. The elements of this array will be passed as the arguments to the function being called. The argArray parameter can be either an array literal or the deprecated arguments property of a function.

在这种情况下,第一个参数不重要(因此为 null),第二个参数很重要,因为数组作为参数传递给 Math.min。这就是这里使用的“技巧”。

[编辑十一月。 2020] 这个回答比较老了。现在(使用 Es20xx)您可以使用 spread syntax将数组传播到 Math.min 的参数。

Math.min(...[1,2,3]);

关于javascript - 如何在javascript中获取数组中的最小元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5442109/

相关文章:

javascript - 将输入保存在数组中并显示所有项目 jquery\javascript

javascript - 如何找到一个字母出现 x 次(以及一次或多次)的所有单词?

javascript - jshint:时髦的代码与分号;如何在这里消除 jshint 对分号的所有提示?

javascript - 方便的自动完成项目排序

javascript - jQuery 悬停处理函数在动态添加类后无法在悬停上工作

javascript - 路由错误。路由 'key1' 的组件必须是 React 组件

javascript - 使用正则表达式从查询字符串中捕获值?

javascript - console.log 是原子的吗?

javascript - Jquery fileupload - 包括表单内的插件

javascript - 输入类型文件更改时如何传递 Angular 值