嗨,我是 Javascript 新手,我想知道是否有更短的方法来解决这个问题
下面给出的数字。我需要在不使用 math.min 的情况下在最小自然情况下找到最小选项,并且我需要使用 for 和 function 命令。
N1 | N2 | N3 | |
---|---|---|---|
选项1 | 10 | 20 | 30 |
选项2 | 40 | 50 | 60 |
选项3 | 70 | 80 | 90 |
选项4 | 100 | 110 | 120 |
我这样做了,但我想知道是否有另一种或更短的方法来解决问题?
const strategyTable = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90],
[100, 110, 120]
];
function findLowestDecisionAndLowestValue(strategyTable) {
let lowestDecision = 1;
let lowestValue = strategyTable[0][0];
for (let i = 0; i < strategyTable[0].length; i++) {
let columnMinimum = strategyTable[0][i]; //
for (let j = 0; j < strategyTable.length; j++) {
if (strategyTable[j][i] < columnMinimum) {
columnMinimum = strategyTable[j][i];
}
}
if (columnMinimum < lowestValue) {
lowestValue = columnMinimum;
lowestDecision = i + 1;
}
}
return { lowestDecision, lowestValue };
}
let { lowestDecision, lowestValue } = findLowestDecisionAndLowestValue(strategyTable);
console.log("Lowest value: " + lowestValue);
console.log("Lowest decision Option " + lowestDecision);
我认为你的代码已经相当高效且可读。但是,如果您想让它更短一些,可以使用reduce方法将两个for循环合并为一个。具体方法如下:
const strategyTable = [
[12500, 5000, 10000],
[7850, 4900, 9730],
[6250, 11600, 8450],
[12300, 9880, 15230]
];
function findLowestDecisionAndLowestValue(strategyTable) {
let lowestDecision = 0;
let lowestValue = Infinity;
for (let i = 0; i < strategyTable[0].length; i++) {
let columnMinimum = strategyTable.reduce((min, row) => row[i] < min ? row[i] : min, Infinity);
if (columnMinimum < lowestValue) {
lowestValue = columnMinimum;
lowestDecision = i + 1;
}
}
return { lowestDecision, lowestValue };
}
let { lowestDecision, lowestValue } = findLowestDecisionAndLowestValue(strategyTable);
console.log("Lowest value: " + lowestValue);
console.log("Lowest decision Option " + lowestDecision);
此版本的代码与您的代码执行相同的操作,但它使用reduce方法来查找每列中的最小值。这消除了对内部 for 循环的需要。 reduce 方法对累加器和数组中的每个元素(从左到右)应用函数,将其减少为单个输出值。
在本例中,它用于查找每列中的最小值。 Infinity值被用作reduce方法的初始值,因此即使列中的所有值都很大,它也能正确识别最小值。