开发者

generate unique visitorId in JavaScript

I need to generate visitorId in JS, max length is 7 chars, valid chars are [0-9][A开发者_C百科-Z], any ideas?


I'm almost certain that you can't do what you want in pure Javascript, because you can't co-ordinate between the different visitors.

With only 7 characters, the range of available values is relatively small - by which I mean, small enough that any pseudo-random assignment of values by the client will almost certainly result in a clash very quickly (see Birthday paradox).

If you try to work around it by, say, appending the time at which the visitor was first seen - this is a good strategy in general, but here it's eating even more into your entropy. If you could encode this time in four characters, you've then got only 3 characters to differentiate between clients arriving during the same second (according to their clocks) and you're going to get a collision again.

Basically, this isn't going to be solvable without either:

  • Some help from the server - i.e. the server embeds a seed number in the page, which can be assured to be unique because it's server-side, you can have the client JS transform this into an alphanumeric ID somehow.
  • Making the character much bigger - if you can have 64 characters in the visitorID, for instance, you can encode the timestamp down to the millisecond, the visitor's IP address and possibly some other unique information, and then a random component. The chance of clashes here would likely head towards the chance of an MD5 hash collision, i.e. the point at which it's acceptable. (But calculate based on what you know about your visitors!)


You have to define the "uniqueness" you want, and then you can do a md5 hash of the "key" values defining your user (for instance, IP)


If you want just a random string, I found this function by googleing:

function randomString(string_length) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    document.randform.randomfield.value = randomstring;
}


function rand( min, max ) {
    if( max ) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    } else {
        return Math.floor(Math.random() * (min + 1));
    }
}

function getVisitorId() {
  var alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var id = '';
  for(var i=0;i<7i++) id+=alpha.charAt(rand(0,35));
  return id;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜