编辑代码

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

}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(binarySearch(4, arr))