var arr = []; // 通过for 生成排好序的测试数组 for (var i = 10; i < 50; i++){ arr.push(i * 2); } // 通过for 测试方法 for (var i = 0; i < 100; i++){ console.log(seek(arr, i), i) } /** * @param arr 要查找的数组 * @param num 要查找的元素 * @returns {*} 元素对应的下标,若不存在,返回-1 */ function seek(arr, num) { return check(0, arr.length) function check(start, end) { var diff = parseInt((end - start) / 2); var middle = start + diff; // console.log(arr[middle], middle, start, end, diff) if (diff == 0){ if (arr[middle] == num){ return middle; } else { return -1; } } if (arr[middle] == num) { return middle; } else if(arr[middle] < num) { return check(middle, end); } else if(arr[middle] > num) { return check(start, middle); } } }