[英]I have no Idea why is my min function not working it keeps on giving me 0 as an answer
So this the function code i came up with I do not know what is wrong with it.所以这是我想出的 function 代码我不知道它有什么问题。 It keeps giving 0 as my code.
它一直给 0 作为我的代码。
function minValue(array) { let min = 0; for (let i = 0; i < array.length; i++) { for (let j = 0; j < array[i].length; j++) { if (array[j][i] == "string") { min = Math.min(min, parseInt(array[j][i])); } else { min = Math.min(min, array[j][i]); } } } return min; } let matrix = [ [57, 71, 37, 99, 62, '83', '95', '54', 38, 25], [8, 64, 100, '51', 43, 21, 21, 33, 11, 43], [67, 25, 45, 67, 88, 72, 74, 77, 53, 38] ]; console.log(minValue(matrix));
I keep on getting 0 as my answer.我不断得到0作为我的答案。
Your function doesn't work because you use 0
as the initial value, and it's smaller than all other values.您的 function 不起作用,因为您使用
0
作为初始值,并且它小于所有其他值。 Use Infinity
as the initial value.使用
Infinity
作为初始值。
Note: you've switch between i
and j
here - array[j][i]
.注意:您已经在
i
和j
之间切换 - array[j][i]
。 I would also remove the condition, and always convert to number (I've used the +
operator here).我还将删除条件,并始终转换为数字(我在这里使用了
+
运算符)。
function minValue(array) { let min = Infinity; for (let i = 0; i < array.length; i++) { for (let j = 0; j < array[i].length; j++) { min = Math.min(min, +array[i][j]); } } return min; } const matrix = [ [57, 71, 37, 99, 62, '83', '95', '54', 38, 25], [8, 64, 100, '51', 43, 21, 21, 33, 11, 43], [67, 25, 45, 67, 88, 72, 74, 77, 53, 38] ]; console.log(minValue(matrix));
Another options is to flatten matrix to a single array, map all items to numbers, and spread into Math.min()
:另一种选择是将矩阵展平为单个数组, map 将所有项目转换为数字,并传播到
Math.min()
:
const minValue = array => Math.min(...array.flat().map(Number)); const matrix = [ [57, 71, 37, 99, 62, '83', '95', '54', 38, 25], [8, 64, 100, '51', 43, 21, 21, 33, 11, 43], [67, 25, 45, 67, 88, 72, 74, 77, 53, 38] ]; console.log(minValue(matrix));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.