Where do I belong-freecodecamp算法题目

Where do I belong(数组排序并找出元素索引)

  1. 要求
    • 给数组排序
    • 找到指定的值在数组的位置,并返回位置对应的索引。
  2. 思路
    • 设定.sort()需要的返回函数
    • 将要搜索的值添加到数组内
    • 用.sort()对数组进行排序
    • 用.indexOf()返回指定值的索引
  3. 代码
    •  1 function where(arr, num) {
       2   // 请把你的代码写在这里
       3   function compareNumbers(a, b) {
       4     return a - b;
       5   }
       6   arr.push(num);
       7   arr.sort(compareNumbers);
       8   return arr.indexOf(num);
       9 }
      10 
      11 where([40, 60], 50);
  4. 相关链接
    • https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
原文地址:https://www.cnblogs.com/ahswch/p/9297113.html