//二分法查找的前提,数组需要是有序的

    1. function getIndex(arr,num){
    2. var len = arr.length,
    3. st = 0,
    4. end = len-1
    5. while(st<=end){
    6. var mid = Math.floor((st+end)/2)
    7. if(num==arr[mid]){
    8. return mid
    9. }else if(num>arr[mid]){
    10. st = mid+1
    11. }else{
    12. end = mid-1
    13. }
    14. }
    15. return arr;
    16. }
    17. var ary=[1,4,7,8,12,34,67,88,99,100]
    1. <script>
    2. var a = [1,3,5,7,9,11,13,15];
    3. var min = 0;
    4. var max = a.length - 1;
    5. var findNum = 11;
    6. while(min <= max){
    7. var middle = parseInt((min+max)/2);
    8. if(findNum > a[middle]){
    9. min = middle + 1;
    10. middle = parseInt((min+max)/2);
    11. }
    12. else if(findNum < a[middle]){
    13. max = middle - 1;
    14. middle = parseInt((min+max)/2);
    15. }
    16. else{
    17. console.log("找到了"+middle);
    18. break;
    19. }
    20. }
    21. </script>

    image.png