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

JavaScript递归调用如何复用同一数组?避免splice改用索引区间操作

How to Reuse the Same Array in Recursive Calls (Without Slicing/Splicing)

Great question! Reusing the original array instead of creating copies with slicing or mutating it with splicing is a smart move—it’s more efficient (avoids unnecessary array allocations) and prevents unintended side effects (like how your current code mutates the input array with splice, which is probably not desirable).

Let’s break down the issues with your existing code first:

  • values[0,middleIndex] doesn’t do what you think it does! That syntax actually accesses the 0 and middleIndex properties of the array object, not creates a subarray. You probably meant values.slice(0, middleIndex), but even slice makes a new array copy.
  • values.splice(0, middleIndex) modifies the original array directly, which will alter the array outside of your function call—definitely a gotcha to avoid.

Here’s the Modified Binary Search Using Start/End Indices

We’ll add two optional parameters: fromIndex (defaulting to 0) and endIndex (defaulting to the array’s length). This lets us work with a "virtual" subarray defined by these bounds, without touching the original array itself.

function binarySearch(values, searchedValue, fromIndex = 0, endIndex = values.length) {
  // If our virtual subarray is empty, the value isn't present
  if (fromIndex >= endIndex) {
    return false;
  }

  // Calculate middle index based on our current bounds
  const middleIndex = Math.floor((fromIndex + endIndex) / 2);
  const middleValue = values[middleIndex];

  if (middleValue === searchedValue) {
    return true;
  } else if (middleValue < searchedValue) {
    // Search the right half: adjust the start index to middle + 1
    return binarySearch(values, searchedValue, middleIndex + 1, endIndex);
  } else {
    // Search the left half: adjust the end index to middle
    return binarySearch(values, searchedValue, fromIndex, middleIndex);
  }
}

Key Details:

  • We use a left-closed, right-open interval ([fromIndex, endIndex)): this means fromIndex is included in our subarray, but endIndex is not. This simplifies boundary calculations and reduces off-by-one error risks.
  • No array copies or mutations—we’re just passing updated index bounds to each recursive call, so the original array stays completely untouched.
  • The default values for fromIndex and endIndex mean you can still call the function the same way as before: binarySearch(myArray, 42) works exactly as expected.

Example Usage:

const numbers = [1, 3, 5, 7, 9, 11];
console.log(binarySearch(numbers, 7)); // true
console.log(binarySearch(numbers, 2)); // false
console.log(numbers); // [1,3,5,7,9,11] (original array is unchanged!)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:22:09