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

如何判断数组元素所属配对为奇数配对还是偶数配对?

解决方案

不需要对原数组进行分块操作,直接通过元素的索引计算就能判断它属于奇数配对还是偶数配对,完全保留一维数组的优势。

核心逻辑

每个配对包含2个元素,我们可以通过元素的索引i直接推导配对组的奇偶性:

  • 把每2个元素视为一组,组的序号从1开始计数(第1组:索引0、1;第2组:索引2、3;第3组:索引4、5...)
  • 只需判断组序号是奇数还是偶数:组序号为奇数时返回true,偶数则返回false

进一步简化计算:组序号的奇偶性等价于Math.floor(i / 2) % 2 === 0——结果为true对应奇数配对,false对应偶数配对。

实现代码

const inputArray = ["a","b","c","d","e","f"];

function doesEntryComeFromOddPair(element, array) {
  const index = array.indexOf(element);
  // 处理元素不在目标数组的边界情况
  if (index === -1) return false;
  // 核心计算逻辑
  return Math.floor(index / 2) % 2 === 0;
}

// 验证预期效果
console.log(doesEntryComeFromOddPair(inputArray[0], inputArray)); // true
console.log(doesEntryComeFromOddPair(inputArray[1], inputArray)); // true
console.log(doesEntryComeFromOddPair(inputArray[2], inputArray)); // false
console.log(doesEntryComeFromOddPair(inputArray[3], inputArray)); // false
console.log(doesEntryComeFromOddPair(inputArray[4], inputArray)); // true
console.log(doesEntryComeFromOddPair(inputArray[5], inputArray)); // true

性能优化

如果能直接传入元素的索引而非元素本身,可避免indexOf的遍历开销,让函数更高效:

function doesEntryComeFromOddPairByIndex(index) {
  return Math.floor(index / 2) % 2 === 0;
}

// 调用示例
console.log(doesEntryComeFromOddPairByIndex(0)); // true
console.log(doesEntryComeFromOddPairByIndex(2)); // false

这种方式既不用修改原数组结构,也能快速得到判断结果,完全保留一维数组的所有优势。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:40:21