JavaScript查找对象属性最大值 处理值相等场景的自定义返回需求
实现方案
你可以先收集所有值等于最大值的键,再根据匹配到的键的数量判断输出内容,具体实现代码如下:
// 第一步:获取对象所有键的集合 const keys = Object.keys(obj); // 可选兼容空对象场景 if (keys.length === 0) { document.getElementById('explain').innerText = "对象为空"; return; } let max = Number.NEGATIVE_INFINITY; const maxKeys = []; // 遍历找最大值,同时收集所有等于最大值的键 for (const key of keys) { const value = obj[key]; if (value > max) { max = value; maxKeys.length = 0; // 出现更大值时清空之前的最大键集合 maxKeys.push(key); } else if (value === max) { maxKeys.push(key); // 和当前最大值相等时直接加入集合 } } let output = ''; if (maxKeys.length === keys.length) { // 所有属性值完全相等 output = "There is no maximum"; } else if (maxKeys.length > 1) { // 存在多个最大值,按示例格式拼接输出 if (maxKeys.length === 2) { output = `${maxKeys[0]} and ${maxKeys[1].replace('Section ', '')} are equal`; } else { // 兼容超过2个最大值的场景 const lastKey = maxKeys.pop().replace('Section ', ''); output = `${maxKeys.join('、').replaceAll('Section ', '')} and ${lastKey} are equal`; } } else { // 仅存在一个最大值,沿用原有输出逻辑 output = `max is: ${maxKeys[0]} with: ${max} points`; } document.getElementById('explain').innerText = output;
场景测试验证
场景1:单最大值(原正常场景)
输入对象:
var obj = { 'Section A': 10, 'Section B': 20, 'Section C': 10 }
输出结果:max is: Section B with: 20 points
场景2:所有属性值完全相等
输入对象:
var obj = { 'Section A': 10, 'Section B': 10, 'Section C': 10 }
输出结果:There is no maximum
场景3:多个属性值同为最大值
输入对象:
var obj = { 'Section A': 20, 'Section B': 20, 'Section C': 10 }
输出结果:Section A and B are equal
内容的提问来源于stack exchange,提问作者Marq
相关产品推荐
相关产品推荐

