【问题标题】:Turn an input string into an array so that each word can be manipulated将输入字符串转换为数组,以便可以操作每个单词
【发布时间】:2017-07-22 23:38:51
【问题描述】:

我正在尝试从 //PROGRAM 1 中创建的输入字符串创建一个数组,以便我可以操作它。一旦创建了数组,我就会发现很多关于如何执行此操作的信息,但我需要先创建该数组。

我只需要将输入字符串转换为分隔每个单词的数组所需的任何函数。我实际上可能输入了代码,即“var res = one.split(”“);”但我不知道下一步该怎么做,这样我就可以获取并记录每个字符的长度,这样我就可以将单词添加到任何超过 5 个字符的单词中。

(以下更新版本。)如何修复第 24 行的错误?

<!DOCTYPE html>
<html>
<head>
<title>Project 1 – Michael Fiorello</title>
<script>
do{
    //MAIN MENU
var input = prompt ("Please enter 1, 2, 3, or exit.");{
//PROGRAM 1-Enter the string to be converted to robot speak
    if(input == "1")
     do{
         var one = prompt ("Please enter a string.");{
          if (one == "") { console.warn("You need to enter something");}
             }

         }while (one == "")//keep repeating program 1 until something is entered, aka cannot be blank.

//PROGRAM 2-Convert the string into robot speak
    else if (input == "2")
        {
          if (one == null) {console.warn ("You need to first enter a String")}
            else {console.log ("String Converted")
                var res = one.split(" ");{
                    for(i = 0, i<Arr.length, i++)
                     if(res[i].length >= 5)
                  {
                      Document.write(Arr.[i]+"-blip");
                  }
                  else{
                      Document.write(Arr.[i]+"-clang");
                  }
                }

                 }
                 }
    //Program 3 Robot Language version of the string will appear in the console
    else if (input == "3")
    {
            alert ("AWESOME!"); 
        }
    else if (input.toLowerCase() == "exit")
        {
        alert ("Thanks for using the ROBOT Language Converter!");
        }
    else 
        {
        alert ("Nope");
        console.warn("You need to enter something");
        }
    }
    }while(input.toLowerCase() != "exit");
</script>
</head>
<body>
<h1></h1>

</body>
</html>

【问题讨论】:

  • “我正在寻找很多关于如何在创建数组后执行此操作,但我需要先创建该数组。” - 是的,.split() (你提到的)是创建数组的方法。您的res 字符串数组,其中每个元素都是一个单词。 res.length 告诉你你有多少字。 res[0].length 告诉你第一个单词的长度。因此,鉴于您说您已经找到了很多关于下一步该做什么的问题,那么问题是什么?
  • 是的,split 已经在做。不确定您真正在寻找什么?拆分后知道,尽管您必须将数组中的每个元素替换为只有字符,即 'last.'.replace(/[^az]/ig, '') 才能获得单词的长度,而无需逗号和句号。
  • 我希望拆分输入的句子,然后检查每个单词的长度。如果它小于 5 我需要添加单词 clang。如果它的长度为 5 或更多,我需要添加 blip。然后在下一个程序中,我需要输出带有 blip 和 clang 的句子
  • 所以最后如果我输入“我讨厌工作”。它会变成“我讨厌叮当的工作昙花一现。”
  • 我该怎么做才能实际操作这些值基本上是个问题。

标签: javascript arrays input words


【解决方案1】:

这就是如何在javascript中拆分字符串

"str".split("") // ["s","t","r"]
"first second".split(" ") // ["first","second"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2016-02-04
    相关资源
    最近更新 更多