Javascript练习:实现用户可调参数的随机字符图案生成功能
实现方案
你需要先生成全#的基础网格,再将指定数量的随机位置替换为目标随机字符,同时做好参数合法性校验即可,修正后的可运行代码如下:
// 获取用户输入并转换为数字 let width = Number(prompt("Choose a Width value")); let height = Number(prompt("Choose a height value")); let randomCount = Number(prompt("Choose the number of random characters")); const baseChar = '#'; // 基础填充字符,可自定义修改 const randomChars = '*'; // 随机字符池,可扩充为多个字符如'*@$%&' // 参数合法性校验 const totalChars = width * height; if (isNaN(width) || isNaN(height) || isNaN(randomCount) || width < 1 || height < 1) { alert("请输入有效的正整数参数"); } else if (randomCount > totalChars) { alert(`随机字符数量不能超过网格总字符数${totalChars}`); } else { // 初始化全基础字符的数组 let gridArr = new Array(totalChars).fill(baseChar); // 生成不重复的随机位置替换为随机字符 let replacedIndexes = new Set(); while (replacedIndexes.size < randomCount) { let randomIndex = Math.floor(Math.random() * totalChars); replacedIndexes.add(randomIndex); } replacedIndexes.forEach(index => { let randomChar = randomChars.charAt(Math.floor(Math.random() * randomChars.length)); gridArr[index] = randomChar; }); // 按宽度拼接成带换行的字符串 let result = ''; for (let i = 0; i < height; i++) { result += gridArr.slice(i * width, (i + 1) * width).join('') + '<br>'; } // 输出结果 document.write(result); }
代码说明
- 所有参数都保留了用户自定义入口,可按需调整基础填充字符、随机字符池内容
- 加入了参数校验逻辑,避免非法输入导致的运行异常
- 使用Set存储随机索引保证随机位置不重复,严格匹配用户输入的随机字符出现次数
内容的提问来源于stack exchange,提问作者ninna
相关产品推荐
相关产品推荐

