gpt4 book ai didi

javascript - 使用 word_number 值对 javascript 数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:52:05 26 4
gpt4 key购买 nike

如何对数组进行排序

var arr = new Array("word_12", "word_59", "word_17");

让我得到

["word_12", "word_17", "word_59"]

谢谢!

最佳答案

您需要编写一个排序方法(您可以编写您喜欢的任何内容),它在 _ 上拆分字符串并将第二部分用作数字排序值。

​    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"

这是一个 fiddle : http://jsfiddle.net/eUvbx/1/

关于javascript - 使用 word_number 值对 javascript 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10921422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com