js sort自定义排序扩展函数

数组自带sort扩展

下面将超链接字符串根据()中的数字进行排序

//字符串数组
let a=["<a href="https://www.giserdqy.com/database/mongodb… target="_blank" rel="noopener">(3)Python是什么?</a>", "<a href="https://www.giserdqy.com/database/mongodb…5" target="_blank" rel="noopener">(1)Python教程</a>", "<a href="https://www.giserdqy.com/database/mongodb…rget="_blank" rel="noopener">(7)Python安装和环境配置</a>"]
//排序传的函数
var compare = function () {
    return function (obj1, obj2) {
        var val1 = parseInt(obj1.substring(obj1.indexOf('(')+1,obj1.indexOf(')')));
        var val2 =parseInt(obj2.substring(obj2.indexOf('(')+1,obj2.indexOf(')')));if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }            
    } 
}
//执行sort,传入compare
a.sort(compare()).join('\n\r');
"<a href="https://www.giserdqy.com/database/mongodb/11195" target="_blank" rel="noopener">(1)Python教程</a>
<a href="https://www.giserdqy.com/database/mongodb/11275" target="_blank" rel="noopener">(2)Python快速入门</a>
<a href="https://www.giserdqy.com/database/mongodb/11192" target="_blank" rel="noopener">(3)Python是什么?</a>
<a href="https://www.giserdqy.com/database/mongodb/11272" target="_blank" rel="noopener">(4)Python的历史</a>
<a href="https://www.giserdqy.com/database/mongodb/11270" target="_blank" rel="noopener">(5)Python功能特点</a>
<a href="https://www.giserdqy.com/database/mongodb/11265" target="_blank" rel="noopener">(6)Python可以开发哪些程序?</a>
<a href="https://www.giserdqy.com/database/mongodb/11198" target="_blank" rel="noopener">(7)Python安装和环境配置</a>
"



发表评论

您的电子邮箱地址不会被公开。

CAPTCHAis initialing...