zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Where do I belong #303

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

挑战

将一个数字插入到一个排序后的数组中,范围该数字的索引号。

代码


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.unshift(num);
  arr.sort(function(a,b){return a-b;});

  var arrNum=0;

  for(var i=0;i<arr.length;i++){
    if(arr[i]===num){
      arrNum=i;
      return arrNum;
    }    
  }

  return arr;

}

getIndexToIns([2, 5, 10], 15);

结果显示

image

帮助

Array.prototype.sort()

来源

https://www.freecodecamp.org/challenges/where-do-i-belong

zilongxuan001 commented 6 years ago

JavaScript的.sort()不能自动比较,必须加上函数,比如从小到大arr.sort(function(a,b){return a-b;})