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

如何用迭代优化Google Apps Script中的列显隐切换脚本?

优化Google Apps Script列显隐切换代码

下面是优化后的代码,解决了原代码重复逻辑过多的问题,同时提升了可读性和执行效率:

function hdud() {
  // 需要切换显隐的列号(对应D、E、K、L、R、S列)
  const targetColumns = [4, 5, 11, 12, 18, 19];
  const sheet = SpreadsheetApp.getActive().getActiveSheet();

  targetColumns.forEach(column => {
    // 三元运算符简化显隐切换逻辑
    sheet.isColumnHiddenByUser(column) ? sheet.showColumns(column) : sheet.hideColumns(column);
  });
}

优化说明:

  • 集中管理目标列:将所有需要切换的列号存入数组,后续维护时只需修改数组元素,无需重复编写相同的判断代码。
  • 减少API调用:仅获取一次当前活动工作表,避免原代码中重复调用SpreadsheetApp.getActive().getActiveSheet(),降低不必要的性能消耗。
  • 简化条件判断:用三元运算符替代原代码中重复的if-else结构,让逻辑更紧凑,代码行数大幅减少。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:52:24