这是我尝试过的:
Math.min([1,2,3])
但只得到NaN
...
最佳答案
使用应用
:
Math.min.apply(null,[1,2,3]); //=> 1
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/