java/golang/js版本号比较
程序员文章站
2024-01-13 22:34:04
...
我们一般使用版本号控制版本,并且做一些判断或者向下兼容。一般版本号会使用semver 规范,格式为 Major.Minor.Patch,其中Major、Minor、Patch均为整数。
比较版本号的大小可参考如下:
java
public static int compareVersion(String srcString, String anotherString) {
String[] v1 = srcString.split("\\.");
String[] v2 = anotherString.split("\\.");
List<String> list1 = new ArrayList<String>(Arrays.asList(v1));
List<String> list2 = new ArrayList<String>(Arrays.asList(v2));
int lim = Math.max(v1.length, v2.length);
while (list1.size() < lim) {
list1.add("0");
}
while (list2.size() < lim) {
list2.add("0");
}
for (int i = 0; i < lim; i++) {
int num1 = Integer.parseInt(list1.get(i));
int num2 = Integer.parseInt(list2.get(i));
if (num1 > num2) {
return 1;
} else if (num1 < num2) {
return -1;
}
}
return 0;
}
public static void main(String[] args) {
System.out.println(compareVersion("1.2.1", "1.2.0")); // 1
System.out.println(compareVersion("1.2.1", "1.2.1")); // 0
System.out.println(compareVersion("1.2.1", "1.2.3")); // -1
}
golang
func compareVersion(src string, other string) int {
v1 := strings.Split(src, ".")
v2 := strings.Split(other, ".")
var lim int
if len(v1) > len(v2) {
lim = len(v1)
} else {
lim = len(v2)
}
for {
if len(v1) >= lim {
break
}
v1 = append(v1, "0")
}
for {
if len(v2) >= lim {
break
}
v2 = append(v2, "0")
}
for i := 0; i < lim; i++ {
num1, _ := strconv.Atoi(v1[i])
num2, _ := strconv.Atoi(v2[i])
if num1 > num2 {
return 1
}
if num1 < num2 {
return -1
}
}
return 0
}
fmt.Println(compareVersion("1.2.1","1.2.0")) // 1
fmt.Println(compareVersion("1.2.1","1.2.1")) // 0
fmt.Println(compareVersion("1.2.1","1.2.2")) // -1
js
function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
var len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (var i = 0; i < len; i++) {
var num1 = parseInt(v1[i])
var num2 = parseInt(v2[i])
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
上一篇: 微信小程序实现列表下拉刷新上拉加载
下一篇: SpringCloud 教程