js 密码生成器,我如何将返回的值组合在一个字符串中

所以我想要做的是,生成一个随机字符/数字并将其连接到一个字符串并将它们组合在一起。我可以使用上面的代码获得一个随机字符/数字,但无法弄清楚如何将它们连接到一个字符串中。len由用户输入,代表字符串的长度(所以如果输入5,随机字符串需要5个字符长)


    function createPassword() {

        var len= document.getElementById('length').value;


        for (let i=0; i<len.length; i++) {

            var random= Math.floor(Math.random()*94)+33

            var char = String.fromCharCode(random)

            var password=''

            password+=char[i]


            console.log(password)

        }

    }


慕田峪7331174
浏览 186回答 2
2回答

缥缈止盈

您只需要在循环外声明密码变量len 是数字,所以不需要 len.length,只需输入 lenchar[i] - 只使用 char,所以我们可以把它变成一行,没有实际的 char 变量 password+=String.fromCharCode(random)我建议提供 len 作为参数,所以只需调用console.log(&nbsp;createPassword(16)&nbsp;)这里函数本身function createPassword(len){&nbsp; &nbsp; var password = '';//declare&nbsp; &nbsp; for(let i=0; i<len; i++){&nbsp; &nbsp; &nbsp; &nbsp; var random = Math.floor(Math.random()*94)+33&nbsp; &nbsp; &nbsp; &nbsp; password += String.fromCharCode(random)&nbsp; &nbsp; }&nbsp; &nbsp; return password;}

慕的地6264312

document.getElementById('generate').addEventListener('click', createPassword)function createPassword(){&nbsp; &nbsp; var len= document.getElementById('length').value;&nbsp; &nbsp; var password=''&nbsp; &nbsp; for(let i=0; i<len; i++){&nbsp; &nbsp; &nbsp; &nbsp; var random= Math.floor(Math.random()*94)+33&nbsp; &nbsp; &nbsp; &nbsp; password+= String.fromCharCode(random)&nbsp; &nbsp; }&nbsp; &nbsp; document.getElementById('result').innerText=password;}这是我正在尝试做的工作版本,以供将来参考。它生成一个带有输入长度的随机字符/数字的密码
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript