javascript - 将 Array1 中的随机值添加到 Array2 直到满足条件
问题描述
两个数组: 1 - userInput 包含用户通过 prompt() 输入的字符串。可以包含 1 到 61 个字符。2 - letterArray 是静态的,包含 9 个字符。
我创建了一个变量 arrayCount 来查找 userArray 的长度。我需要创建一个 if/else 语句,它将一个随机字符从 letterArray 附加到 userInput 的末尾,直到 arrayCount 等于 61,此时我可以继续执行函数的其余部分(这适用于我)。
我只知道足够多的 javascript 来知道什么是可能的,但对如何完成它只有一个模糊的想法。到目前为止,我的尝试都是徒劳的。
我试过 .push 但我很确定我的语法很差。已经在互联网上搜索了几个小时,我的大部分答案都是从 w3schools.com 收集的。
这是我的代码的样子:
function chartFunction() {
var formInput = prompt("Please enter your phrase", "This eye chart is absolutely fantastic");
var capsInput = formInput.toUpperCase();
var userInput = capsInput.replace(/\s+/g, '');
var letterArray = ["E", "F", "Z", "K", "L", "O", "I", "D"]
var rand1 = letterArray[Math.floor(Math.random() * letterArray.length)];
var arrayCount = userInput.length
if(arrayCount !== 61) {
userInput.push(letterArray[Math.floor(Math.random() * letterArray.length)]);
} else {
document.write("<p>");
document.write(userInput[0]);
document.write("<p>");
document.write(userInput[1],userInput[2]);
解决方案
在您的代码中,您尝试.push
在string
. 根据您的问题描述,我想出了以下解决方案,如果我遗漏了什么,请告诉我。
function chartFunction() {
const MAX_CHAR = 61;
let userInput = prompt("Please enter your phrase", "This eye chart is absolutely fantastic");
// replace space and convert to uppercase
userInput = userInput.replace(/\s+/g, '').toUpperCase();
if (userInput.length < MAX_CHAR) {
const letterArray = ["E", "F", "Z", "K", "L", "O", "I", "D"];
const numberOfCharsToGenerate = MAX_CHAR - userInput.length;
/*
Array(numberOfCharsToGenerate) => generates an empty array set with the length specified
.fill('') => fill the empty array set with an empty string, which makes the actual array with value(here value is '')
.map() => modifies the array with the random string
.join() => converts array to string with delimiter ''
*/
userInput = userInput + Array(numberOfCharsToGenerate).fill('')
.map(() => letterArray[Math.floor(Math.random() * letterArray.length)]).join('');
}
// printing final 'userInput' and its length
console.log(userInput, userInput.length);
// remaining logic here
}
chartFunction();
推荐阅读
- javascript - 如何从 textarea 获取 html、css、js 代码并编译
- python - 我似乎无法解决此代码(python 速成课程)
- javascript - nodejs中的基本udp NAT遍历?
- python - 从多个类组成 PyQt5 UI
- python - 如何调整图像大小但使用python保留像素值
- python - 如何在 django-rest-framework-simple-jwt 中使用自定义模型用户
- machine-learning - 是什么导致这个 LSTM 的准确率如此之低?
- java - 我的工具栏太高了,因为它看起来很丑,下面的屏幕被裁剪了,我该如何解决?
- django - 如何在 Django 模型中设置字段常量
- python - for in for 循环(for 并行工作)