使用word_number值排序javascript数组 [英] sort javascript array with word_number values
本文介绍了使用word_number值排序javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何对数组进行排序
var arr = new Array("word_12", "word_59", "word_17");
因此我得到
["word_12", "word_17", "word_59"]
谢谢!
推荐答案
您需要编写一个排序方法(您可以编写任何您喜欢的方法),它将字符串拆分为_和使用第二部分作为数字排序值。
you need to write a sort method (you can write any that you like) which splits the string on the _ and uses the second part as a numeric sort value.
function sortOnNum(a,b){
//you'll probably want to add a test to make sure the values have a "_" in them and that the second part IS a number, and strip leading zeros, if these are possible
return (a.split("_")[1] * 1 > b.split("_")[1] * 1)? 1:-1;// I assume the == case is irrelevant, if not, modify the method to return 0 for ==
}
var ar = new Array ("foo_1", "foo_19", "foo_3", "foo_1002");
ar.sort(sortOnNum); //here you pass in your sorting function and it will use the values in the array against the arguments a and b in the function above
alert(ar); // this alerts "foo_1,foo_3,foo_19,foo_1002"
这是一个小提琴:
http://jsfiddle.net/eUvbx/1/
这篇关于使用word_number值排序javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文