你能帮我吗?... 我在Javascript中有一个数组,我需要顺序升序,我的问题是……我只需要订购第一个号码……"-"向左....
This is my array .
["20140615-http://localhost:8080/PROYECTO/upload/ORBTHZK/image_ORBTHZK.gif", "20140617-http://localhost:8080/PROYECTO/upload/ORBITHCITY/image_ORBITHCITY.png", "20140601-http://localhost:8080/PROYECTO/upload/423445/image_423445.gif"]
And I need This…
["20140601-http://localhost:8080/PROYECTO/upload/423445/image_423445.gif", "20140615-http://localhost:8080/PROYECTO/upload/ORBTHZK/image_ORBTHZK.gif", "20140617-http://localhost:8080/PROYECTO/upload/ORBITHCITY/image_ORBITHCITY.png"]
奇怪的是,在数组上调用sort()
工作得很好。下面是我在节点控制台中所做操作的副本:
var arr = ["20140615-http://localhost:8080/PROYECTO/upload/ORBTHZK/image_ORBTHZK.gif", "20140617-http://localhost:8080/PROYECTO/upload/ORBITHCITY/image_ORBITHCITY.png", "20140601-http://localhost:8080/PROYECTO/upload/423445/image_423445.gif"];
arr.sort()
[ '20140601-http://localhost:8080/PROYECTO/upload/423445/image_423445.gif',
'20140615-http://localhost:8080/PROYECTO/upload/ORBTHZK/image_ORBTHZK.gif',
'20140617-http://localhost:8080/PROYECTO/upload/ORBITHCITY/image_ORBITHCITY.png' ]
可能根据您的环境而有所不同,但它在Node以及所有主流浏览器中都得到支持。所以如果你的目标浏览器是旧的/边缘情况下的YMMV。
试试这个:
function sortArr(arr, f, isNum) {
var l = arr.length,
data = new Array(l);
for(var i=0; i<l; ++i)
data[i] = [f(arr[i]), arr[i]];
data.sort(isNum
? function(a,b){ return a[0]-b[0]; }
: function(a,b){ return a[0]<b[0] ? -1 : a[0]>b[0] ? 1 : 0; }
);
for(var i=0; i<l; ++i) arr[i] = data[i][1];
}
var arr = ["20140615-http://localhost:8080/PROYECTO/upload/ORBTHZK/image_ORBTHZK.gif", "20140617-http://localhost:8080/PROYECTO/upload/ORBITHCITY/image_ORBITHCITY.png", "20140601-http://localhost:8080/PROYECTO/upload/423445/image_423445.gif"];
sortArr(arr, function(str){ return str.split('-')[0]; }, true);
虽然在这种情况下调用sort()
就足够了(参见@Paul的回答),但您可以轻松地创建自己的排序函数:
array.sort(function(a, b) {
a = a.split('-')[0];
b = b.split('-')[0];
if (a > b)
return 1;
if (a < b)
return -1;
return 0;
});
参见JSFiddle的示例。您可以在MDN上了解更多关于Array.prototype.sort()
的信息。