以下是软件版本号:
"1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"
我怎么比较呢?
假设正确的顺序是:
"1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"
想法很简单…
读第一个数字,然后,第二个,第三个…
但是我不能将版本号转换为浮点数…
你也可以像这样看到版本号:
"1.0.0.0", "1.0.1.0", "2.0.0.0", "2.0.0.1", "2.0.1.0"
这样可以更清楚地看到背后的想法。
但是,我怎样才能把它转换成计算机程序呢?
基于Idan的精彩回答,下面的函数semverCompare通过了语义版本2.0.0的大多数情况。了解更多要点。
function semverCompare(a, b) {
if (a.startsWith(b + "-")) return -1
if (b.startsWith(a + "-")) return 1
return a.localeCompare(b, undefined, { numeric: true, sensitivity: "case", caseFirst: "upper" })
}
它返回:
-1: a < b
0: a == b
1: a > b
这个非常小,但非常快的比较函数接受每个段的任何长度和任何数字大小的版本号。
返回值:
-如果a < b,则数字< 0
-如果是> b,则为> 0
如果a = b - 0
所以你可以使用它作为array。sort()的比较函数;
编辑:修正了版本剥离尾随零识别“1”和“1.0.0”相等的错误
function cmpVersions (a, b) {
var i, diff;
var regExStrip0 = /(\.0+)+$/;
var segmentsA = a.replace(regExStrip0, '').split('.');
var segmentsB = b.replace(regExStrip0, '').split('.');
var l = Math.min(segmentsA.length, segmentsB.length);
for (i = 0; i < l; i++) {
diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
if (diff) {
return diff;
}
}
return segmentsA.length - segmentsB.length;
}
// TEST
console.log(
['2.5.10.4159',
'1.0.0',
'0.5',
'0.4.1',
'1',
'1.1',
'0.0.0',
'2.5.0',
'2',
'0.0',
'2.5.10',
'10.5',
'1.25.4',
'1.2.15'].sort(cmpVersions));
// Result:
// ["0.0.0", "0.0", "0.4.1", "0.5", "1.0.0", "1", "1.1", "1.2.15", "1.25.4", "2", "2.5.0", "2.5.10", "2.5.10.4159", "10.5"]
我认为这是一个值得分享的实现,因为它简短,简单,但功能强大。请注意,它只使用数字比较。通常它会检查version2是否比version1晚,如果是,则返回true。假设您有version1: 1.1.1和version2: 1.1.2。它遍历两个版本的每个部分,将它们的部分相加如下:对于版本1(1 + 0.1)然后(1.1 + 0.01),对于版本2(1 + 0.1)然后(1.1 + 0.02)。
function compareVersions(version1, version2) {
version1 = version1.split('.');
version2 = version2.split('.');
var maxSubVersionLength = String(Math.max.apply(undefined, version1.concat(version2))).length;
var reduce = function(prev, current, index) {
return parseFloat(prev) + parseFloat('0.' + Array(index + (maxSubVersionLength - String(current).length)).join('0') + current);
};
return version1.reduce(reduce) < version2.reduce(reduce);
}
如果你想从版本列表中找到最新的版本,那么这可能是有用的:
function findLatestVersion(versions) {
if (!(versions instanceof Array)) {
versions = Array.prototype.slice.apply(arguments, [0]);
}
versions = versions.map(function(version) { return version.split('.'); });
var maxSubVersionLength = String(Math.max.apply(undefined, Array.prototype.concat.apply([], versions))).length;
var reduce = function(prev, current, index) {
return parseFloat(prev) + parseFloat('0.' + Array(index + (maxSubVersionLength - String(current).length)).join('0') + current);
};
var sums = [];
for (var i = 0; i < versions.length; i++) {
sums.push(parseFloat(versions[i].reduce(reduce)));
}
return versions[sums.indexOf(Math.max.apply(undefined, sums))].join('.');
}
console.log(findLatestVersion('0.1000000.1', '2.0.0.10', '1.6.10', '1.4.3', '2', '2.0.0.1')); // 2.0.0.10
console.log(findLatestVersion(['0.1000000.1', '2.0.0.10', '1.6.10', '1.4.3', '2', '2.0.0.1'])); // 2.0.0.10
你可以使用JavaScript的localeCompare方法:
a.localeCompare(b, undefined, {numeric: true})
这里有一个例子:
"1.1".localeCompare("2.1.1", undefined, {numeric: true}) => -1
"1.0.0".localeCompare("1.0", undefined, {numeric: true}) =>
"1.0.0".localeCompare("1.0.0", undefined, {numeric: true}) => 0
你可以使用带有选项的String#localeCompare
sensitivity
Which differences in the strings should lead to non-zero result values. Possible values are:
"base": Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
"accent": Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A.
"case": Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A.
"variant": Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A.
The default is "variant" for usage "sort"; it's locale dependent for usage "search".
numeric
Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are true and false; the default is false. This option can be set through an options property or through a Unicode extension key; if both are provided, the options property takes precedence. Implementations are not required to support this property.
var版本=[" 2.0.1”、“2.0”、“1.0”、“1.0.1”,“2.0.0.1”);
版本。sort((a, b) => a.localeCompare(b, undefined, {numeric: true,灵敏度:'base'}));
console.log(版本);