使用sort()以降序获取数字(Using sort() to get numbers in descending order)

编程入门 行业动态 更新时间:2024-10-10 03:26:15
使用sort()以降序获取数字(Using sort() to get numbers in descending order)

我正在努力完成这个卡塔 。 试图解决这个问题,我已经看过这个帖子,但我想我正在按照它在那里说的那样做。

我究竟做错了什么? 为什么不按降序对数字进行排序? 到目前为止这是我的代码:

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.

更多推荐

本文发布于:2023-07-19 07:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1175418.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   降序   sort   order   descending

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!