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

高效处理对象数组:负值时交换source与target属性值

高效处理大型对象数组的最后一个元素

先明确需求:我们有一个包含71000个元素的对象数组(示例如下),需要高效处理数组的最后一个对象——当valueN为负值时,交换它的source和target属性,同时把valueN转为绝对值。

示例数组:

[ 
  { source: "France", target: "Morocco", timeN: "2008", valueN: "252.35" }, 
  { source: "France", target: "Morocco", timeN: "2009", valueN: "424.12" }, 
  { source: "France", target: "Morocco", timeN: "2010", valueN: "152.24" }, 
  { source: "France", target: "Morocco", timeN: "2011", valueN: "-342.19" } 
]

下面分享几个可行的方案:

方案1:简洁易读的实现(@Nina Scholz)

这个方案用了解构赋值,代码非常简洁直观,日常开发中用起来很顺手:

const lastItem = arr[arr.length - 1];
const value = +lastItem.valueN;

if (value < 0) {
  // 解构交换source和target
  [lastItem.source, lastItem.target] = [lastItem.target, lastItem.source];
  // 转回字符串类型保持格式一致
  lastItem.valueN = Math.abs(value).toString();
}

方案2:性能优先的优化版(@Emil S. Jørgensen)

如果你的场景对性能要求极高(毕竟数组有7万+元素),这个方案会更合适——它减少了不必要的类型转换操作,执行效率更高:

const lastIndex = arr.length - 1;
const item = arr[lastIndex];
const numValue = parseFloat(item.valueN);

if (numValue < 0) {
  // 临时变量交换属性,比解构略快一点
  const tempSource = item.source;
  item.source = item.target;
  item.target = tempSource;
  
  // 如果后续不需要字符串类型的valueN,直接存数值类型能进一步提升性能
  item.valueN = -numValue;
  // 要是必须保留字符串格式,再加toString():
  // item.valueN = (-numValue).toString();
}

最终选型与性能对比

测试下来所有方案都能满足需求,我最终采用了@Nina Scholz的简洁方案,代码可读性拉满。不过跟踪执行时间后发现,@Emil S. Jørgensen的方案性能最优,尤其是不把valueN转换回字符串的时候,速度提升更明显。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:49:41