首页 > 解决方案 > 将 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]);

标签: javascript

解决方案


在您的代码中,您尝试.pushstring. 根据您的问题描述,我想出了以下解决方案,如果我遗漏了什么,请告诉我。

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();


推荐阅读