如何创建一个生成随机3字母序列的函数?

时间:2014-02-18 08:57:20

标签: javascript random

我需要将网页与'random.js'文件连接起来,我希望我已经正确完成了该文件,并创建了一个名为'GenerateSequence'的函数,该函数生成3个随机字母。我已经将3'RonteChar'插入体内,但我不确定它们到底在哪里。最后,页面需要看起来像这样

<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
 <title>Random Letter Sequence</title>

 <script type="text/javascript" src="random.js"></script>

 <script type="text/javascript">
 function GenerateSequence()
 {

 }
</script>
</head>

<body>
<h2>Generate 3-Letter Sequence</h2>

sequence =  RandomChar('abcdefghijklmnopqrstuvwxyz') +
        RandomChar('abcdefghijklmnopqrstuvwxyz') +
        RandomChar('abcdefghijklmnopqrstuvwxyz');

<hr>
<h3>You Random 3-Letter Sequence<h3>
<div id="outputDiv"></div>
</body>
</html> 

1 个答案:

答案 0 :(得分:0)

function GenerateSequence(){
  var result = "";
  var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  for(var i=0;i<3;i++){
      result += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
  }
  return result;
}
window.onload = function(){
  document.getElementById('goButton').onclick=function() {  
    document.getElementById('outputDiv').innerHTML = GenerateSequence();
  }
}