首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UserID函数JavaScript

UserID函数JavaScript
EN

Stack Overflow用户
提问于 2018-02-02 18:15:26
回答 1查看 53关注 0票数 1

我正在尝试从userAgent和Date函数中生成一个UserID。我还想了解回调函数(我仍然不理解它(JS Noob))。因此,我构建了以下示例:

代码语言:javascript
复制
var storage = window.localStorage; 
var storageUserId = storage.getItem("userID"); 
var text = "";  

function userID(callback){
  var agent = window.navigator.userAgent;
  var now = new Date(); 
    try{
        callback(agent, now);
    }catch(e){}
}

function hasher(agent,now){
    var hash = 0;
    var arr = []; 
    for(var i = 0; i < arguments.length; i++){
      var pars = arguments[i]; 
      for(var j = 0; j < pars.length; j++){
         var charI = pars.charCodeAt(j);
         hash = ((hash<<5)-hash)+charI;
         hash = hash & hash; // Convert to 32bit integer
         hash = hash.toString();
      }
    }
  console.log(hash + "|" + hash);
}

userID(hasher);

结果应该类似于"9834917834|8293479273“(显示格式的示例数字)。第一个数字散列座席第二个数字散列日期。我在这里得到了散列逻辑形式:http://mediocredeveloper.com/wp/?p=55

也许有一种更好的方法可以做到这一点:)

我真的很感谢你的帮助!

非常感谢!

最好的,安东

EN

回答 1

Stack Overflow用户

发布于 2018-02-02 18:24:24

您应该将散列循环提取到一个新函数中:

代码语言:javascript
复制
function hash(str){
  var hash = 0;
  for(const char of str){        
    const charCode =  char.charCodeAt(0);            
    hash = ((hash<<5)-hash)+charCode;
  }
  hash = hash & hash; // Convert to 32bit integer

  return hash.toString();
}

因此,为了得到你想要的散列,你只需要调用它两次:

代码语言:javascript
复制
function getUserID(){
  return hash(window.navigator.userAgent) + "|" + hash("" + new Date);
}

(PS:你知道new Date每毫秒都会改变吗?)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48580444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档