js判断对多个版本号进行排序怎么做?

1.例如现在存在一组版本号,['0.1.1', '2.3.3', '0.3002.1', '4.2', '4.3.5', '4.3.4.5'],怎么对这个版本号进行排序,实现最后排序的结果为['4.3.5','4.3.4.5','2.3.3','0.3002.1','0.1.1'];不知道各位大神有什么好的实现方法?

蛊毒传说
浏览 1675回答 3
3回答

德玛西亚99

var arr=['0.1.1', '2.3.3', '0.3002.1', '4.2', '4.3.5', '4.3.4.5'];    arr.sort(function(a,b){        return a>b?-1:1;    });    console.log(arr);

慕田峪4524236

var arr = ['0.1.1', '2.3.3', '0.3002.1', '4.2', '4.3.5', '4.3.4.5']arr.sort((a,b)=>{    var items1 = a.split('.')    var items2 = b.split('.')    var k = 0    for (let i in items1) {      let a1 = items1[i]      let b1 = items2[i]      if (typeof a1 === undefined) {        k = -1        break      } else if (typeof b1 === undefined) {        k = 1        break      } else {        if (a1 === b1) {          continue        }        k = Number(a1) - Number(b1)        break      }    }    return k})console.log(arr)

茅侃侃

// 使用的是选择排序const versionSort = version => {&nbsp; const temp = version.map(v => v.split('.'));&nbsp; for (let i = 0; i < temp.length; i++) {&nbsp; &nbsp; let minIndex = i;&nbsp; &nbsp; for (let j = i; j < temp.length; j++) {&nbsp; &nbsp; &nbsp; for (let k = 0; k < temp[j].length; k++) {&nbsp; &nbsp; &nbsp; &nbsp; const current = +temp[j][k],&nbsp; &nbsp; &nbsp; &nbsp; min = +temp[minIndex][k];&nbsp; &nbsp; &nbsp; &nbsp; if (current < min) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; minIndex = j;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // 只要不等,就立刻结束最内层遍历!&nbsp; &nbsp; &nbsp; &nbsp; if (current !== min) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; [temp[i], temp[minIndex]] = [temp[minIndex], temp[i]];&nbsp; }&nbsp; return temp.map(v = > v.join('.'))};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript