我正在努力完成这个卡塔 。 试图解决这个问题,我已经看过这个帖子,但我想我正在按照它在那里说的那样做。
我究竟做错了什么? 为什么不按降序对数字进行排序? 到目前为止这是我的代码:
function descendingOrder(n){ let newN = n.toString().split(' ').sort(function(a,b){return b-a}).join(); return parseInt(newN); }测试通过:值== 0测试通过:值== 1预期:987654321,而得到:123456789
提前致谢
I'm trying to complete this kata. Trying to figure it out, I've seen this thread but I think I'm doing it as it says in there.
What am I doing wrong? Why doesn't it sort the numbers in descending order? This is my code so far:
function descendingOrder(n){ let newN = n.toString().split(' ').sort(function(a,b){return b-a}).join(); return parseInt(newN); }Test Passed: Value == 0 Test Passed: Value == 1 Expected: 987654321, instead got: 123456789
Thanks in advance
最满意答案
您需要使用空字符串''拆分字符串以获取单个数字并将其与空字符串连接。
使用不属于字符串的字符进行拆分会产生具有单个值的数组。 后来加入的数组返回此单个元素。 这就是为什么你得到与输入相同的结果值。
没有指定分隔符的Array#join ,返回带有值的逗号分隔字符串。
let newN = n.toString().split('').sort(function (a, b) { return b - a; }).join('');最后,你可以采取一元加+ ,就像
return +newN;获得数值。
顺便说一下,使用parseInt ,你可以指定一个基数,因为前导零的字符串可以转换为八进制数。
You need to split the string with an empty string '' to get single digits and join it with an empty string.
Splitting with a character which is not part of the string results in an array with a single value. A later joined array returns this single element. That is why you get the same value as result as the input.
Array#join without a specified separator, returns a comma separated string with the values.
let newN = n.toString().split('').sort(function (a, b) { return b - a; }).join('');At the end, you could take an unary plus +, like
return +newN;for getting an numerical value.
BTW, with the use of parseInt, you may specify a radix, because strings with leading zero may be converted to an octal number.
更多推荐
发布评论