You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于最大值与参数更新对象数组中的值(JavaScript实现)

数组元素val值更新实现方案

需求说明

拥有一个对象数组,传入updateValue和uid两个参数,按以下规则更新数组元素的val值:

  • 若元素id与uid相同,将该元素的val更新为updateValue;
  • 若元素id不等于uid,且val≥updateValue且≤原数组中val的最大值,则将val自增1;
  • 其他情况保持原val值不变。

示例与预期输出

示例1

输入数组与参数:

const list = [
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 3, color: 'yellow' },
  { id: 44, val: 4, color: 'black' },
  { id: 55, val: 2, color: 'indigo' },
];

const uid = 13;
const updateValue = 2;

预期输出:

[
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 2, color: 'yellow' },
  { id: 44, val: 4, color: 'black' },
  { id: 55, val: 3, color: 'indigo' },
];

示例2

输入数组与参数:

const list1 = [
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 5, color: 'yellow' },
  { id: 44, val: 4, color: 'black' },
  { id: 55, val: 2, color: 'indigo' },
];

const uid = 44;
const updateValue = 2;

预期输出:

[
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 6, color: 'yellow' },
  { id: 44, val: 2, color: 'black' },
  { id: 55, val: 3, color: 'indigo' },
];

原代码问题分析

你提供的代码存在以下问题:

  1. 语法错误:对象字面量中不能用=赋值,需使用key: value形式;map回调括号未闭合;变量result重复声明。
  2. 逻辑错误:用非null元素的数量代替了原数组val的最大值,不符合需求;变量名混淆(updateVal与updateValue);处理val为null的逻辑冗余。

修正后的代码

function updateListValues(arr, uid, updateValue) {
  // 计算原数组中val的最大值(排除null)
  const validVals = arr.filter(item => item.val !== null).map(item => item.val);
  const maxVal = validVals.length > 0 ? Math.max(...validVals) : -Infinity;
  
  return arr.map(item => {
    // 规则1:id匹配时更新val
    if (item.id === uid) {
      return { ...item, val: updateValue };
    }
    
    // 规则2:id不匹配且val在指定范围内时自增
    if (item.val !== null && item.val >= updateValue && item.val <= maxVal) {
      return { ...item, val: item.val + 1 };
    }
    
    // 规则3:其他情况返回原对象副本
    return { ...item };
  });
}

// 测试示例1
const list = [
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 3, color: 'yellow' },
  { id: 44, val: 4, color: 'black' },
  { id: 55, val: 2, color: 'indigo' },
];
console.log(updateListValues(list, 13, 2));

// 测试示例2
const list1 = [
  { id: 10, val: null, color: 'red' },
  { id: 23, val: 1, color: 'blue' },
  { id: 13, val: 5, color: 'yellow' },
  { id: 44, val: 4, color: 'black' },
  { id: 55, val: 2, color: 'indigo' },
];
console.log(updateListValues(list1, 44, 2));

代码说明

  • 提前计算原数组val的最大值,避免在map中重复计算,提升效率;
  • 严格按需求规则依次判断,逻辑清晰;
  • 使用对象展开运算符创建新对象,避免修改原数组元素,保持数据不可变性;
  • 单独处理val为null的情况,确保不会触发自增逻辑。

内容的提问来源于stack exchange,提问作者Codelearn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:23:07