编辑代码

function binarySearch(arr, k) {
  let left = 0
  let right = arr.length - 1
  while(left <= right) {
    let middle = Math.floor((left + right) / 2)
    if(arr[middle] === k) {
      return middle
    } else if(arr[middle] > k) {
      right = middle - 1
    } else {
      left = middle + 1
    }
  }
  return -1
}

const nums = [6, 17, 25, 34, 52, 63, 85]
const key = 6
console.log(binarySearch(nums, key)) // 输出 0