如何正确排序的整数数组

编程入门 行业动态 更新时间:2024-10-24 16:32:53
本文介绍了如何正确排序的整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

试图从一个阵列的最高值和最低值,我知道将只包含整数似乎比我想象的更难?

Trying to get the highest and lowest value from a array that I know will contain only integers seems to be harder than I thought?

var numArray = [140000, 104, 99]; numArray = numArray.sort(); alert(numArray[0] + ", " + numArray[numArray.length - 1]);

我预计这将显示99,140000。相反,它显示104 99。如此看来,这种排序是处理值作为字符串?

I'd expect this to show "99, 140000". Instead it shows "104, 99". So it seems the sort is handling the values as strings?

什么办法让排序函数实际上排序整数价值?

Any way to get the sort function to actually sort on integer value?

推荐答案

默认情况下,排序方法字母顺序​​排列的元素。要排序数字只是添加用于处理数字排序的新方法(sortNumber,如下图所示) -

By default the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

function sortNumber(a,b) { return a - b; } var numArray = [140000, 104, 99]; numArray.sort(sortNumber); alert(numArray.join(","));

更多推荐

如何正确排序的整数数组

本文发布于:2023-11-29 22:00:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647747.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数组   如何正确

发布评论

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

>www.elefans.com

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