【问题标题】:how can i get fix random number as taking input name in javascript我怎样才能得到修复随机数作为在javascript中输入名称
【发布时间】:2021-10-05 18:02:30
【问题描述】:

实际上,我想要一个固定的数字,比如爱情计算器帮助我找出这个问题。 Brandon 号码不应该更改相同的名称,我输入相同的名称,所以我应该得到相同的号码。给我一些提示或代码。在 JavaScript 中。

【问题讨论】:

  • 你想要像哈希这样的东西。您可以将每个字符转换为一个代码点,并以您喜欢的任何方式组合它们。

标签: javascript


【解决方案1】:
var yourName = document.getElementById('inputName').value;

// Returns a random integer from 0 to 99:
var randomNumber = Math.floor(Math.random() * 100);

var nameWithRandomNumber = yourName.concat(randomNumber);

【讨论】:

  • “我输入了相同的名字,所以我应该得到相同的数字”
【解决方案2】:

如果你想为相同的输入获得相同的输出,它不是随机的。 您正在寻找的是一个散列函数。

根据您的要求(长度、唯一性/冲突),这可能会有所帮助: String to unique integer hashing

【讨论】:

    【解决方案3】:

    如果您在给出相同输入时需要相同的“随机”输出,则您正在寻找hash function

    类似这样的:

    function hashCode(string) {
        let hash = 0;
        if (string.length == 0) {
            return hash;
        }
        for (let i = 0; i < string.length; i++) {
            let char = string.charCodeAt(i);
            hash = ((hash<<5)-hash)+char;
            hash = hash & hash;
        }
        return hash;
    }
    

    在下面的sn-p中应该可以看到只要输入相同的字符串,就会输出相同的数字。

    function hashCode(string) {
        let hash = 0;
        if (string.length == 0) {
            return hash;
        }
        for (let i = 0; i < string.length; i++) {
            let char = string.charCodeAt(i);
            hash = ((hash<<5)-hash)+char;
            hash = hash & hash;
        }
        return hash;
    }
    
    let input = document.querySelector("#input")
    let output = document.querySelector("#output")
    
    input.addEventListener("keyup", () => {
      output.value = hashCode(input.value)
    })
    <p>Enter text here</p>
    <input type="text" id="input">
    
    <p>'Random' number outputted here</p>
    <input type="text" disabled="disabled" value="" id="output">

    【讨论】:

      猜你喜欢
      • 2023-01-18
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 2018-03-16
      • 1970-01-01
      相关资源
      最近更新 更多