我正在尝试通过最后4个子串排列我的数组,这些子串是数字并且它无法正常工作。 代码是
function sortArray(){
top10.sort(function(a, b){
var ax = a.substr(6, 4);
var bx = b.substr(6, 4);
return bx>ax;
console.log(top10);
});
}
top10 = [];
$.get('user_db_hm.txt', function(myContentFile)
{
top10 = myContentFile.split("\n");
sortArray();
}, 'text');
console.log是
["欺骗 - 9 "," zombi - 8 "," rofls - 7 "," kombi - 6 "," abcdf - 5"," johny - 4 "," kolio - 22 "," gosho - 2 "," rapis - 14 "," pesho - 1 "]
答案 0 :(得分:0)
您需要返回sort()
生成的新排序数组,并确保将子字符串转换为数字,以便正确比较它们。
试试这个:
function sortArray(){
return top10.sort(function(a, b){
var ax = Number(a.substr(7, 4));
var bx = Number(b.substr(7, 4));
return bx>ax;
});
}
答案 1 :(得分:0)
您的计划有两个问题,
parseInt
将字符串转换为Intger substr
将数据作为- 22
返回,这不是您想要的所以,试试这个
top10.sort(function(a, b){
var ax = a.substr(7, 4);
var bx = b.substr(7, 4);
ax.trim();
bx.trim();
return parseInt(bx)>parseInt(ax);
});
console.log(top10);
答案 2 :(得分:0)
<强> jsBin demo 强>
function strNum(v){ return +v.match(/\d+/)||''; }
function sortArray( arr ){
arr.sort(function(a, b){
var ax = strNum(a);
var bx = strNum(b);
return bx>ax;
});
console.log(arr);
}
$.get("user_db_hm.txt", function( data ){
sortArray( data.split("\n") );
}, "text");
日志:
[&#34; kolio - 22&#34;,&#34; rapis - 14&#34;,&#34; dupes - 9&#34;,&#34; zombi - 8&#34;,&# 34; rofls - 7&#34;,&#34; kombi - 6&#34;,&#34; abcdf - 5&#34;,&#34; johny - 4&#34;,&#34; gosho - 2&# 34;,&#34; pesho - 1&#34;]