如何在每次加载页面时创建唯一ID?

时间:2013-09-02 13:17:45

标签: javascript random unique

每次页面加载时,我都需要创建任意长度的随机唯一字符串,以便我可以用它标记周围的东西,以防止可能覆盖现有的对象属性?我认为代码会像:

var
   uid = generate_uid();

1 个答案:

答案 0 :(得分:0)

//  I think I got it
//
function generate_uid( prefix ) {
    var
        tmp1   = "",
        tmp2   = "",
        locase = "abcdefghijklmnopqrstuvwxyz",
        tf     = function () { return Math.random() > .5; },
        r,
        l;

    for (var i = 0, len = locase.length; i < len; i++) {
        tmp1 += ( ( tf() ) ? locase[i].toUpperCase() : locase[i] );
    }
    l = ( tmp1 += String( Date.now ? Date.now() : ( new Date() ).getTime() ) ).length;
    for (
        ; l
        ; (
            r      = Math.floor( Math.random() * ( l-- ) ),
            tmp2  += tmp1.charAt( r ),
            tmp1   = tmp1.substring( 0, r ) + tmp1.substr( r + 1 )
        )
    );
    return prefix ? String( prefix ) + tmp2 : tmp2;
}
console.log( generate_uid("fnid_") );
//
//  fnid_2JGZCMWSyrQaNhD10k83p91LTF073X6oiv9Be5u
//