如何在javascript中获取数组中的min元素? [英] How to get the min elements inside an array in javascript?

查看:83
本文介绍了如何在javascript中获取数组中的min元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我的尝试:

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

但只能获得 NaN ...

推荐答案

使用 apply

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

来自devguru


Function.apply( thisArg [,argArray])
apply方法允许你调用一个
函数并指定在上下文中将引用的关键字

那个功能。 thisArg参数
应该是一个对象。在被调用函数的
上下文中,
这将引用thisArg。 apply方法的第二个
参数是
数组。这个数组的元素将
作为参数传递给被调用的
函数。 argArray
参数可以是数组
literal或函数的弃用参数
属性。

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 。这就是这里使用的'技巧'。

In this case the first argument is of no importance (hence: null), the second is, because the array is passed as arguments to Math.min. So that's the 'trick' used here.

这篇关于如何在javascript中获取数组中的min元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆