试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。
var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)
我希望这是99 104 140000。相反,它显示的是104、14万、99。看起来排序是把值当做字符串处理的。
有没有办法让排序函数对整数值进行排序?
试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。
var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)
我希望这是99 104 140000。相反,它显示的是104、14万、99。看起来排序是把值当做字符串处理的。
有没有办法让排序函数对整数值进行排序?
当前回答
这个答案与一些现有的答案是等价的,但是ECMAScript 6箭头函数提供了一个更紧凑的语法,允许我们在不牺牲可读性的情况下定义一个内联排序函数:
numArray = numArray.sort((a, b) => a - b);
现在大多数浏览器都支持它。
其他回答
这个答案与一些现有的答案是等价的,但是ECMAScript 6箭头函数提供了一个更紧凑的语法,允许我们在不牺牲可读性的情况下定义一个内联排序函数:
numArray = numArray.sort((a, b) => a - b);
现在大多数浏览器都支持它。
试试下面的代码:
HTML:
<div id="demo"></div>
JavaScript代码:
<script>
(function(){
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
})();
</script>
你可以简单地排序数字数组
常量数字=[13,17,14,19,16]; 让温度; for(let i=0;i<num.length;i++){ for(let j=i+1;j<num.length;j++){ if(num[i]>num[j]){ 温度=数字[i] 数字[i]=数字[j] 数字[j]=温度 } } } 控制台.log(数字);
下面的'numerically'函数作为回调函数提供时,在许多情况下用于对数字数组进行数字排序:
function numerically(a, b){
return a-b;
}
array.sort(numerically);
但在一些罕见的情况下,数组包含非常大的负数,当a-b小于JavaScript可以处理的最小数字时,可能会发生溢出错误。
所以用数字表示函数的更好方法如下:
function numerically(a, b){
if(a < b){
return -1;
} else if(a > b){
return 1;
} else {
return 0;
}
}
sort_mixed
Object.defineProperty(Array.prototype,"sort_mixed",{
value: function () { // do not use arrow function
var N = [], L = [];
this.forEach(e => {
Number.isFinite(e) ? N.push(e) : L.push(e);
});
N.sort((a, b) => a - b);
L.sort();
[...N, ...L].forEach((v, i) => this[i] = v);
return this;
})
try a =[1,'u',"V",10,4,"c"," a "].sort_mixed();console.log (a)