子数组的最大值
max value from subarray
我想从 array1 数组的子数组中获取最大值。
var array1 = [[4, 2, 7, 1], [20, 70, 40, 90], [1, 2, 0]];
let one = array1.slice(0,1);
let two = array1.slice(1,2);
let three = array1.slice(2,3);
console.log(one);
console.log(two);
console.log(three);
我的结果是:
> Array [Array [4, 2, 7, 1]]
> Array [Array [20, 70, 40, 90]]
> Array [Array [1, 2, 0]]
然后我尝试从一个、两个和三个变量中获取最大值,但始终是错误 [NaN]。
console.log(Math.max(...one)); => Nan
我的 JS 不是很好,如果有任何帮助,我将不胜感激。谢谢
您可以尝试使用 map
函数,并为每个子数组调用 Math.max
,这将为子数组 return 一个单独的值。
const array1 = [[4, 2, 7, 1], [20, 70, 40, 90], [1, 2, 0]];
const maxValues = array1.map(item => Math.max(...item));
console.log(maxValues);
slice
函数 returns 另一个数组。如果数组中有一项,它将 return 包含一个元素的数组。
console.log(Math.max(...one)); => Nan
因为slice
returns来自输入数组的数组(即one
是一个2d数组),你需要得到第 0 个索引
let one = array1.slice(0,1)[0];
同样
let two = array1.slice(1,2)[0];
let three = array1.slice(2,3)[0];
现在console.log(Math.max(...one));
会给你正确的值
要从所有数组中获取最大值,请尝试
console.log(Math.max(...one,...two,...three)); //spread with comma
获取单个数组
console.log(array1.map( s => Math.max.apply(null, s));
我想从 array1 数组的子数组中获取最大值。
var array1 = [[4, 2, 7, 1], [20, 70, 40, 90], [1, 2, 0]];
let one = array1.slice(0,1);
let two = array1.slice(1,2);
let three = array1.slice(2,3);
console.log(one);
console.log(two);
console.log(three);
我的结果是:
> Array [Array [4, 2, 7, 1]]
> Array [Array [20, 70, 40, 90]]
> Array [Array [1, 2, 0]]
然后我尝试从一个、两个和三个变量中获取最大值,但始终是错误 [NaN]。
console.log(Math.max(...one)); => Nan
我的 JS 不是很好,如果有任何帮助,我将不胜感激。谢谢
您可以尝试使用 map
函数,并为每个子数组调用 Math.max
,这将为子数组 return 一个单独的值。
const array1 = [[4, 2, 7, 1], [20, 70, 40, 90], [1, 2, 0]];
const maxValues = array1.map(item => Math.max(...item));
console.log(maxValues);
slice
函数 returns 另一个数组。如果数组中有一项,它将 return 包含一个元素的数组。
console.log(Math.max(...one)); => Nan
因为slice
returns来自输入数组的数组(即one
是一个2d数组),你需要得到第 0 个索引
let one = array1.slice(0,1)[0];
同样
let two = array1.slice(1,2)[0];
let three = array1.slice(2,3)[0];
现在console.log(Math.max(...one));
会给你正确的值
要从所有数组中获取最大值,请尝试
console.log(Math.max(...one,...two,...three)); //spread with comma
获取单个数组
console.log(array1.map( s => Math.max.apply(null, s));