Where do I belong (freeCodeCamp)

先给数组排序,然后找到指定的值在数组的位置,最后返回位置对应的索引。

举例:where([1,2,3,4], 1.5) 应该返回 1。因为1.5插入到数组[1,2,3,4]后变成[1,1.5,2,3,4],而1.5对应的索引值就是1

同理,where([20,3,5], 19) 应该返回 2。因为数组会先排序为 [3,5,20]19插入到数组[3,5,20]后变成[3,5,19,20],而19对应的索引值就是2

//

先对传入数组排序,然后通过遍历,找出插入点位置

注意array.sort()方法的参数只可以是一个比较方法

function where(arr, num) {
  // 请把你的代码写在这里
  var array=arr.sort(function(a,b){
    return a-b;//排序函数 function();
  });
 
  var postion=0;
  for(var i=0;i<arr.length;i++){
    if(num<=array[i]){
      postion=i;
      break;
    }
    else{
      array.push(num);//这里是插入的数字比数组元素大的情况,通过push()添加到数组中,然后postion获取数组末尾元素索引
      postion=array.length;
    }
    
  }
  return postion;
}

where([2, 5, 10], 19);

猜你喜欢

转载自www.cnblogs.com/doudou2018/p/9610822.html