我正在尝试编写一个函数来查找数组数组中的最小数字。
已经尝试过这个,但我真的不知道当数组上有数组时该怎么做。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9]
const min = Math.min(arr)
console.log(min)
最佳答案
通过使用 ES6,您可以使用 spread syntax ...
,它接受一个数组作为参数。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const min = Math.min(...arr);
console.log(min);
使用 ES5,您可以采用 Function#apply
,取 this
以及参数作为数组。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const min = Math.min.apply(null, arr);
console.log(min);
对于非扁平数组,采用扁平化函数,例如
const
flat = array => array.reduce((r, a) => r.concat(Array.isArray(a) ? flat(a) : a), []),
array = [[1, 2], [3, 4]],
min = Math.min(...flat(array));
console.log(min);
关于javascript - 找到数组的数组中最小的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54268846/