我需要使用for循环将2个随机字母添加到文本框中的字符串中,并在单击按钮时在加密的字符串框中返回。
因此,例如,如果输入cat,它可能会像cynarwtpp一样返回。我是for循环的新手,不确定如何从这里开始,我需要使用一个循环通过字母数组的for循环。任何帮助将不胜感激。
的Javascript:
<script type="text/javascript">
var uncoded_array = uncoded.split("");
var coded_str = "";
var alphabet = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z");
</script>
HTML:
<form action="">
Enter a String: <input type="text" name="uncoded" ></br>
<input type="button" value="cipher" onClick=document.forms[0].coded.value= ></br>
Encrypted String: <input type="text" name="coded" ></br>
答案 0 :(得分:0)
<强> HTML 强>
Enter a String: <input type="text" id="uncoded" />
<input type="button" value="cipher" onclick="cypher(); return false;" />
Encrypted String: <input type="text" id="coded" />
<强> JS 强>
function cypher() {
var coded = document.getElementById('coded');
var uncoded = document.getElementById('uncoded');
coded.value = uncoded.value.split('').map(function (char) {
return char + randomLetter() + randomLetter();
}).join('');
}
function randomLetter() {
return Math.random().toString(36).replace(/[^a-zA-Z]/gi, '')[0];
}
答案 1 :(得分:0)
这是一个简单的方法。
1)从这个answer我学会了从数组中选择随机元素。
var item1 = alphabet[Math.floor(Math.random()*alphabet.length)];
var item2 = alphabet[Math.floor(Math.random()*alphabet.length)];
在你的情况下,来自数组的2个随机字母。
2)在 for iteration
中,我使用了字符串长度并用于在每个字母后添加随机元素并连接在一起。
var alphabet = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z");
var original = "cat";
var encrypted = "";
for (var i=0; i<original.length; i++ ) {
var item1 = alphabet[Math.floor(Math.random()*alphabet.length)];
var item2 = alphabet[Math.floor(Math.random()*alphabet.length)];
encrypted += original[i] + item1 + item2;
}
alert(encrypted);
答案 2 :(得分:0)
这是一个执行字符串操作的简单函数。只需输入第一个表单输入的值,并将其结果转储到第二个表单输入中。
function cipher(str) {
var rand,
output = '',
chars = 'abcdefghijklmnopqrstuvwxyz';
for (i=0; i<str.length; i++) {
output += str[i];
for (j=0; j<2; j++) {
output += chars[Math.floor(Math.random() * chars.length)];
}
}
return output;
}
cipher('cat');