欢迎光临散文网 会员登陆 & 注册

碎片时间学编程「288]:将字符串哈希为数字

2023-03-21 12:16 作者:路条编程  | 我要投稿


将输入字符串散列为整数。

  • 使用String.prototype.split()和Array.prototype.reduce()方法创建输入字符串的散列,利用位移。

const sdbm = str => {  let arr = str.split('');  return arr.reduce(    (hashCode, currentVal) =>      (hashCode =        currentVal.charCodeAt(0) +        (hashCode << 6) +        (hashCode << 16) -        hashCode),    0  );};

示例:

sdbm('name'); // -3521204949

更多内容请访问我的网站:https://www.icoderoad.com


碎片时间学编程「288]:将字符串哈希为数字的评论 (共 条)

分享到微博请遵守国家法律