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

如何简化这两个JavaScript函数的代码实现?

简化方案

当然可以简化,这两个函数逻辑高度重复,只是访问数组的索引不同,下面提供几种实用的简化方式:

方式一:精简单个函数写法

用三元表达式替代冗余的if-else,同时省去不必要的变量声明,让代码更紧凑:

red_messages_disabled_p1() {
  return this.status.red_messages[0] === null ? 'none' : 'inline-block';
},
red_messages_disabled_p2() {
  return this.status.red_messages[1] === null ? 'none' : 'inline-block';
},

方式二:提取通用函数(推荐)

把重复的逻辑抽成一个接受索引参数的通用函数,彻底消除代码重复,后续修改逻辑时只需维护一处:

// 通用逻辑函数
getRedMessageDisplay(index) {
  return this.status.red_messages[index] === null ? 'none' : 'inline-block';
},

// 原函数改为调用通用函数
red_messages_disabled_p1() {
  return this.getRedMessageDisplay(0);
},
red_messages_disabled_p2() {
  return this.getRedMessageDisplay(1);
},

如果是在Vue等框架的模板中使用,甚至可以直接调用getRedMessageDisplay(index),不需要再单独定义red_messages_disabled_p1和red_messages_disabled_p2这两个函数,进一步精简代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:31:34