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

如何编写依赖索引的JavaScript函数,实现每N次交替变更alter返回值?

实现基于index的alter参数计算函数

首先梳理你需要的输出序列规律:
根据给定的输入输出对应关系,最终的alter值序列是:
1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0...

可以看到,从第1个元素(index=0)之后,每两个相同值为一组,交替切换0和1。

实现方案

可以通过纯函数直接计算,完全依赖输入的index参数,不依赖外部状态或调用顺序:

const getAlterParam = (index: number): number => {
  // 核心逻辑:通过(index+1)//2的奇偶性判断,再取反得到目标值
  return 1 - Math.floor((index + 1) / 2) % 2;
};

逻辑验证

逐个验证给定的输入场景:

  • index=0: Math.floor((0+1)/2)=0 → 0%2=0 → 1-0=1 ✔️
  • index=1: Math.floor((1+1)/2)=1 → 1%2=1 → 1-1=0 ✔️
  • index=2: Math.floor((2+1)/2)=1 → 1%2=1 → 1-1=0 ✔️
  • index=3: Math.floor((3+1)/2)=2 → 2%2=0 → 1-0=1 ✔️
  • index=4: Math.floor((4+1)/2)=2 → 2%2=0 → 1-0=1 ✔️
  • index=5: Math.floor((5+1)/2)=3 → 3%2=1 → 1-1=0 ✔️
  • index=6: Math.floor((6+1)/2)=3 → 3%2=1 → 1-1=0 ✔️
  • index=7: Math.floor((7+1)/2)=4 → 4%2=0 → 1-0=1 ✔️

完全符合你需要的输入输出逻辑,而且是纯函数,不管调用顺序如何,只要输入相同的index就会返回相同的结果,避免了之前实现中依赖外部状态的问题。

另一种可读性更强的写法

如果觉得上面的一行逻辑不够直观,也可以拆分成更清晰的步骤:

const getAlterParam = (index: number): number => {
  if (index === 0) {
    return 1;
  }
  // 从index=1开始,每两个元素为一组
  const groupIndex = Math.floor((index - 1) / 2);
  // 偶数组返回0,奇数组返回1
  return groupIndex % 2 === 0 ? 0 : 1;
};

这个写法和前面的逻辑等价,只是拆分了步骤,可读性更好,适合需要维护代码的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:15:31