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

如何将代码中的三元运算符转换为if...else条件语句

将三元运算符转换为if...else条件语句的解决方案

你只需要将reduce的箭头函数改为多行形式,通过if...else语句替代三元运算符的逻辑即可,同时可以提前计算平均分避免重复调用函数:

function getBestStudent (students) {
  const bestAverageMark = students.reduce((a, b) => {
    // 提前计算两个学生的平均分,避免重复调用getAverageMark
    const averageA = getAverageMark(a);
    const averageB = getAverageMark(b);
    
    if (averageA > averageB) {
      return a;
    } else {
      return b;
    }
  });
  return bestAverageMark;
}

说明:

  • 原代码的三元运算符getAverageMark(a) > getAverageMark(b)? a : b逻辑是:如果a的平均分高于b,就返回a,否则返回b
  • 转换后的if...else完全等价于原逻辑,同时拆分了重复的函数调用,代码可读性更强
  • 由于箭头函数改为多行,必须手动添加return语句,否则会返回undefined导致逻辑错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:30:55