
正文
Where do I belong-freecodecamp算法题目
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Where do I belong(数组排序并找出元素索引)
-
要求
- 给数组排序
- 找到指定的值在数组的位置,并返回位置对应的索引。
-
思路
- 设定.sort()需要的返回函数
- 将要搜索的值添加到数组内
- 用.sort()对数组进行排序
- 用.indexOf()返回指定值的索引
-
代码
-
function where(arr, num) {
// 请把你的代码写在这里
function compareNumbers(a, b) {
return a - b;
}
arr.push(num);
arr.sort(compareNumbers);
return arr.indexOf(num);
} where([40, 60], 50);
-
-
相关链接
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort







