Where do I belong
rasoft opened this issue · comments
Challenge Where do I belong has an issue.
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
.
Please describe how to reproduce this issue, and include links to screenshots if possible.
My code:
function where(arr, num) {
// 请把你的代码写在这里
var array = Array.from(arr);
if (array.indexOf(num) === -1)
array.push(num);
array.sort(function (a, b) {
return a > b;
});
return array.indexOf(num);
}
where([10, 20, 30, 40, 50], 35);
//where([10, 20, 30, 40, 50], 30);
@rasoft 你的 sort
方法用的不对。。
因为要求 compareFunction
必须返回正数、负数或者 0,所以你可以写:
arr.sort((a, b) => a - b)
也可以写:
arr.sort((a, b) => {
if (a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
});
特定的情况下(比如这道题)可以写:
arr.sort((a, b) => a > b ? 1 : -1);
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
你现在的写法,排序的结果是错的,可以自己验证下