[英]javascript array.sort not working with integers
我在javascript数组排序和整数方面遇到问题。 我定义了以下功能:
function sortA(a,b){
return a - b;
}
function sortD(a,b){
return b - a;
}
然后在jquery $ .each中,将一些内容放入数组中:
$('.'+sort_column).each(function(index, value) {
var current_num = $.trim($(this).text())
current_num = parseInt(current_num, 10); //convert to integer for numeric sorting.
valuesArr.push(current_num);
console.log(typeof index); //just checking...this shows number in the console
});
var sort_asc = valuesArr.sort(sortA);
var sort_desc = valuesArr.sort(sortD);
console.log(sort_asc);
console.log(sort_desc);
但是在控制台中,我以相同的顺序获取数组。
//console
[1214500, 1214499, 1214497, 1214481, 1214432, 1214421, 1214419, 1214418, 1214369, 1214045, 1205691]
[1214500, 1214499, 1214497, 1214481, 1214432, 1214421, 1214419, 1214418, 1214369, 1214045, 1205691]
奇怪的是,如果我在字符串末尾附加一个字符串,则排序有效
console.log( valuesArr.sort(sortD) + "asdf");
console.log( valuesArr.sort(sortA) + "asdf");
//console
[1214500,1214499,1214497,1214481,1214432,1214421,1214419,1214418,1214369,1214045,1205691asdf]
[1205691,1214045,1214369,1214418,1214419,1214421,1214432,1214481,1214497,1214499,1214500asdf]
我不知道为什么我什至尝试过,但是你去了。 这是我第一次使用这种方法,因此我很可能错过了一些基本的知识。 非常感谢您的帮助!
.sort()
[MDN]对数组进行原位排序。 变量sort_asc
和sort_desc
引用相同的数组,因此输出是相同的。
您可以像下面这样简单地更改您的sortA()
和sortD()
:
function sortA(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
function sortD(arr) {
return arr.sort(function(a, b) {
return b - a;
});
}
然后使用如下所示:
var myarr = [1214500, 1214499, 1214497, 1214481, 1214432, 1214421,
1214419, 1214418, 1214369, 1214045, 1205691];
sortA(myarr);
sortD(myArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.