nsIVersionComparator 编辑

xpcom/base/nsIVersionComparator.idlScriptable This interface is used to compare version strings. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0)

Version strings are dot-separated sequences of version-parts. A version-part consists of up to four parts, all of which are optional:

<number-a><string-b><number-c><string-d (everything else)>

A version-part may also consist of a single asterisk "*" which indicates * "infinity". Numbers are base-10, and are zero if left out. Strings are compared bytewise.
For additional backwards compatibility, if "string-b" is "+" then "number-a" is incremented by 1 and "string-b" becomes "pre".

1.0pre1
  < 1.0pre2
    < 1.0 == 1.0.0 == 1.0.0.0
      < 1.1pre == 1.1pre0 == 1.0+
        < 1.1pre1a
          < 1.1pre1
            < 1.1pre10a
              < 1.1pre10

Implemented by: @mozilla.org/xpcom/version-comparator;1. The service can be accessed directly via Services.vc after loading Services.jsm or with the following code:

var versionComparator = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
                                  .getService(Components.interfaces.nsIVersionComparator);

Method overview

long compare(in ACString A, in ACString B);

Methods

compare()

Compare two version strings.

long compare(
  in ACString A,
  in ACString B
);
Parameters
A
The first version.
B
The second version.
Return value

If A and B are two version being compared, and the return value

  • is smaller than 0, then A < B
  • equals 0 then Version, then A==B
  • is bigger than 0, then A > B

Example

function compareVersions(a,b) {
 var x = Services.vc.compare(a,b);
 if(x == 0)
   return a + "==" + b;
 else if(x > 0)
   return a + ">" + b;
 return a + "<" + b;
}
dump(compareVersions("1.0pre", "1.0"));

Example - Compare current browser version

This example here uses nsIXULAppInfo component to get the version of the browser that the code is running in. See here: nsIXULAppInfo

Components.utils.import("resource://gre/modules/Services.jsm");
var curentBrowserVersion = Services.appinfo.platformVersion; //example: '31.*'

var compareToThisVersion = '25.*';

var compareResult = Services.vc.compare(curentBrowserVersion, compareToThisVersion);

if (compareResult == -1) {
    //currentBrowserVersion is less than '25.*' (compareToThisVersion)
} else if (compareResult == 0) {
    //currentBrowserVersion is '25.*' (compareToThisVersion)
} else if (compareResult == 1) {
   //currentBrowserVersion is greater than '25.*' (compareToThisVersion)
} else {
   //will never get here as Services.vc.compare only returns -1, 0, or 1
}

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:106 次

字数:4716

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文