打印地图中最高值的键



我创建了以下映射:

(function getLakes() {
let lakes = new Map ([['Caspian Sea', 560], ['Tarn Hows', 53], ['Crater Lake', 324], ['Lake Tanganyika', 803], ['Lake Vostok', 546],
['Lake Baikal', 897]]);
let fathom = 1.829;
console.log("The deepest lake is " +  Math.max(...lakes.values())*fathom);
})();

除了记录值,我还想记录密钥,这样我就可以得到以下额外的行:"最深的湖是贝加尔湖。">

我不知道该怎么做——有人知道吗?

谢谢!

展开Map并对条目([key, value]对(使用Array.find()。使用destructuring获取湖泊的名称(键(。

const lakes = new Map([
['Caspian Sea', 560],
['Tarn Hows', 53],
['Crater Lake', 324],
['Lake Tanganyika', 803],
['Lake Vostok', 546],
['Lake Baikal', 897]
]);
const fathom = 1.829;
const max = Math.max(...lakes.values());
const [lake] = [...lakes].find(([, v]) => v === max);
console.log(`The deepest lake is ${max * fathom}`);
console.log(`The deepest lake is ${lake}`);

您可以编写自己的自定义逻辑,而不是使用Math.max。请参阅下面的代码示例。

let lakes = new Map ([['Caspian Sea', 560], ['Tarn Hows', 53], ['Crater Lake', 324], ['Lake Tanganyika', 803], ['Lake Vostok', 546],
['Lake Baikal', 897]]);
let fathom = 1.829;
let maxValue,maxKey;
for (let [key, value] of lakes.entries()) {
if(!maxValue || maxValue < value){
maxValue = value;
maxKey = key;
}
}
console.log("The deepest lake is " + maxKey + ' = ' + (maxValue*fathom) );

您可以减少条目:

const [lake, depth] = [...lakes.entries()]
.reduce((a, b) => a[1] > b[1] ? a : b);
console.log(`Lake ${lake} has the depth ${depth}`);

最新更新