How to use javascript math on version number

I use jQuery to get the browser version as follows:

var x = $.browser.version;

I get a line like this: 1.9.1.1

Now, I want to make an assessment, so if x is> = 1.9.1, then do something. Unfortunately, with a few decimal points, I cannot execute parseFloat (), because it converts 1.9.1.1 to 1.9, and the if rating will be consistent with version 1.9.0 (which I don't want).

Has anyone figured out a way to make the number of versions (with a few decimal places) into something that can be used as a number for evaluation (or some other way to accomplish what I'm trying to do here)?

Thanks -

+3
source share
4 answers

- string.split,

// arr[0] = 1
// arr[1] = 9
// arr[2] = 1
// arr[3] = 1
var arr = ($.browser.version).split('.');

post

, JSON

function parseVersionString (str) {
    if (typeof(str) != 'string') { return false; }
    var x = str.split('.');

    // parse from string or default to 0 if can't parse 
    var maj = parseInt(x[0]) || 0;
    var min = parseInt(x[1]) || 0;
    var bld = parseInt(x[2]) || 0;
    var rev = parseInt(x[3]) || 0;
    return {
        major: maj,
        minor: min,
        build: bld,
        revision: rev
    }
}

var version = parseVersionString($.browser.version);
// version.major == 1
// version.minor == 9
// version.build == 1
// version.revision == 1
+7

versionCmp():

function versionCmp(v1, v2) {
    v1 = String(v1).split('.');
    v2 = String(v2).split('.');

    var diff = 0;
    while((v1.length || v2.length) && !diff)
        diff = (+v1.shift() || 0) - (+v2.shift() || 0);

    return (diff > 0) - (diff < 0);
}

:

function valueOfVersion(ver) {
    ver = String(ver).split('.');

    var value = 0;
    for(var i = ver.length; i--;)
        value += ver[i] / Math.pow(2, i * 8) || 0;

    return value;
}

, 256 (- ) (.. ).

+1

, cmp:

// perform cmp(a, b)
// -1 = a is smaller
// 0 = equal
// 1 = a is bigger
function versionCmp(a, b) {
  a = a.split(".");
  b = b.split(".");
  for(var i=0; i < a.length; i++) {
    av = parseInt(a[i]);
    bv = parseInt(b[i]);
    if (av < bv) {
      return -1;
    } else if (av > bv) {
      return 1;
    }
  }
  return 0;    
}

console.log(versionCmp("1.1.2.3", "1.2.1.0"));  // should be -1
console.log(versionCmp("1.19.0.1", "1.2.0.4"));  // should be 1
console.log(versionCmp("1.2.3.4", "1.2.3.4"));  // should be 0
0

, . , .

-3
source

Source: https://habr.com/ru/post/1712935/


All Articles