JavaScript 生成 12 个不重复字符的代码示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>WebCat</title>
<script src="js/jquery.min.js"></script>
<script src="js/wc-3.0.6.min.js"></script>
</head>
<body>
<h1 id="title">Hello world</h1>
<p id="p1">工程创建成功!</p>
<script>
const options = ['1','2','3','4','5','6','7','8','9','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'];
let selected = [];
while(selected.length < 12) {
let randomIndex = Math.floor(Math.random() * options.length);
let randomChar = options[randomIndex];
if(selected.indexOf(randomChar) === -1) {
selected.push(randomChar);
}
}
p1.textContent = selected.join(' ');
</script>
</body>
</html>
<p><strong>代码解释:</strong></p>
<ol>
<li>
<p><strong>定义字符数组:</strong></p>
<ul>
<li><code>const options = ['1','2','3','4','5','6','7','8','9','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'];</code> 定义一个包含所有可能字符的数组 <code>options</code>。</li>
</ul>
</li>
<li>
<p><strong>创建空数组:</strong></p>
<ul>
<li><code>let selected = [];</code> 创建一个空数组 <code>selected</code> 用于存储生成的随机字符。</li>
</ul>
</li>
<li>
<p><strong>循环生成随机字符:</strong></p>
<ul>
<li>使用 <code>while(selected.length < 12)</code> 循环,直到 <code>selected</code> 数组中包含 12 个字符为止。</li>
<li>在循环中,使用 <code>Math.floor(Math.random() * options.length)</code> 生成一个随机索引,并使用该索引从 <code>options</code> 数组中获取一个随机字符 <code>randomChar</code>。</li>
<li>使用 <code>selected.indexOf(randomChar) === -1</code> 检查 <code>randomChar</code> 是否已存在于 <code>selected</code> 数组中,如果不存在则将 <code>randomChar</code> 添加到 <code>selected</code> 数组中。</li>
</ul>
</li>
<li>
<p><strong>显示结果:</strong></p>
<ul>
<li><code>p1.textContent = selected.join(' ');</code> 将 <code>selected</code> 数组中的所有字符用空格连接起来,并将其设置为 <code>p1</code> 元素的文本内容。</li>
</ul>
</li>
</ol>
<p><strong>代码运行结果:</strong></p>
<p>运行代码后,<code>p1</code> 元素将显示 12 个不重复的字符。例如:</p>
<pre><code>B 7 H 3 F Z P 1 W 9 S
</code></pre>
<p><strong>总结:</strong></p>
<p>这段代码使用了循环和条件判断来生成 12 个不重复的随机字符。代码中使用 <code>indexOf</code> 方法来检查字符是否已存在于数组中,确保生成的字符都是唯一的。</p>
原文地址: https://www.cveoy.top/t/topic/obwE 著作权归作者所有。请勿转载和采集!