试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。
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。看起来排序是把值当做字符串处理的。
有没有办法让排序函数对整数值进行排序?
当前回答
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)
其他回答
为了创建这种排序,你必须传递一个函数来检查哪个先出现。
在函数中定义你想检查的值:a.id - a.id
const myJson = [ {id: 1, name: 'one'}, {id: 4, name: 'four'}, {id: 2, name: ' 2 '}, {id: 3, name: ' 3 '} ]; //提供要检查的sort方法 const myNewSort = myJson。排序(函数(a, b) { 返回a.id - b.id; }); console.log('my new sort',myNewSort)
这个答案与一些现有的答案是等价的,但是ECMAScript 6箭头函数提供了一个更紧凑的语法,允许我们在不牺牲可读性的情况下定义一个内联排序函数:
numArray = numArray.sort((a, b) => a - b);
现在大多数浏览器都支持它。
数组中。Sort默认使用字母排序,而不是数字排序。
要支持数字,请添加如下的like
var numArray = [140000, 104, 99];
numArray.sort((a, b) => a - b); // <-- Ascending
numArray.sort((a, b) => b - a); // <-- Descending
console.log(numArray);
输出:
试试下面的代码:
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>
提升 Const移动= [200,450,- 400,3000,-650,- 130,70,1300];
如果返回值小于0,则A将在B之前 如果返回值是> 0,那么B会在A之前
movements.sort((a, b) => {
if (a > b) return 1; //- (Switch order)
if (a < b) return -1; //- (Keep order)
});
A -当前值,b -下一个值。
下行 运动。排序((a, b) => { If (a > b)返回-1;// - (Keep) 如果(a < b)返回1;// - (Switch) });
! 改进,最佳解决方案!
movements.sort ((a, b) => a - b); // Same result!
如果a < b是负数(开关) 如果a < b是负数(Keep)