【问题标题】:While loop to print vowels and other elements on a new line in JavaScriptWhile循环在JavaScript中的新行上打印元音和其他元素
【发布时间】:2019-12-21 12:53:03
【问题描述】:

尝试按出现的顺序在新行上打印单词中的任何元音。 然后在打印完所有元音后对每个常量执行相同的操作。

我尝试过使用中断和开关盒,但代码不起作用。

function vowelsAndConsonants(s) {
    var atom = s.length;
    var i = 0;
    while (i <= atom)
    {
        if (s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' || s[i] === 'u') {
            console.log('\n' + s[i]);
        }
        else {
            console.log('\n' + s);
        }
    }

}

我希望输出如下:

a
i
o

然后是辅音出现的顺序:

t
p
r

【问题讨论】:

    标签: javascript while-loop


    【解决方案1】:

    HackerRank 第 2 天:循环

    function vowelsAndConsonants(s) {
        let conso ="";
        for(var i=0;i<s.length;i++){
            if((s[i]=="a")||(s[i]=="e")||(s[i]=="i")||(s[i]=="o")||
            (s[i]=="u")){
                console.log(s[i])
            }else{
                conso += s[i]+"\n";
            }
        }
        console.log(conso);
    }
    

    【讨论】:

      【解决方案2】:

      我们也可以使用以下代码解决问题。 [ Hackerrank Day2 解决方案 ]

      function vowelsAndConsonants(s) {
          // Create an array of vowels
          const vowels = ['a','e','i','o','u'];
          // Split up the String and Convert it to an Array
          const letters = s.split('');
          // Check for vowels
          for(let i in letters){
              if(vowels.includes(letters[i])){
                  // Print vowels on a new line for each characters.
                  console.log(letters[i]);
              }
          }
          // Check for consonants
          for(let i in letters){
              if(!(vowels.includes(letters[i]))){
                  // Print consonants on a new line for each characters.
                  console.log(letters[i]);
              }
          }
      }
      const test = "javascript";
      vowelsAndConsonants(test);

      【讨论】:

        【解决方案3】:

        访问:https://www.w3schools.com/code/tryit.asp?filename=GQP0X4ZZEKNQ 以更好地查找结果。

        在下面的帮助下,我们可以用简单的方法来区分元音和辅音

          let strOne = "javascriptloopsAI";  // take any string
        
          //String convert into lower case
         var str = strOne.toLowerCase();  
        let vowelarr = ['a','e','i','o','u'];  //  use vowels array
        
         //  here's we are splitting str string with space.
        let strArr = [...str];  
        
        var html='';
        var htmlV='';
        
        //for loop for strArr 
        for (i = 0; i < strArr.length; i++)
        {
           let field='';
           //for loop for vowelarr 
           for (j = 0; j < vowelarr.length; j++)
           {
              if(strArr[i]==vowelarr[j])
              {
                  field=strArr[i];
                  htmlV += strArr[i]+'</br>'  // adding only vowels in htmlv variable
              }
           
            }
            if(strArr[i]!=field)
            {
              html += strArr[i]+'</br>'    //adding only  consonants in htmlv variable
            }
        }
        document.getElementById("demo").innerHTML = htmlV;  
        document.getElementById("demo1").innerHTML = html;
        <p id="demo"></p>
        <p id="demo1"></p>

        【讨论】:

          【解决方案4】:
          function vowelsAndConsonants(s) {
          let vowels = [];
          let consonas = [];
          for(var i=0; i<s.length ; i++) {
              if((s[i]=='a')||(s[i]=='e')||(s[i]=='i')||(s[i]=='o')||(s[i]=='u')){
                  vowels.push(s[i])
              } else {
                  consonas.push(s[i]);
              }
          }
          
          let concatArr = [...vowels, ...consonas];
          for (let i of concatArr) {
              console.log(i);
          }
          

          }

          【讨论】:

            【解决方案5】:
            function vowelsAndConsonants(s){
                let strC='';
                for(var i=0; i<s.length ; i++)
                {
                    if((s[i]=='a')||(s[i]=='e')||(s[i]=='i')||(s[i]=='o')||(s[i]=='u')){
                        console.log(s[i]);
                    }
                    else{
                        strC=strC.concat(s[i]).concat('\n');
                    }
                }
                console.log(strC)
            }
            vowelsAndConsonants('magic')
            

            【讨论】:

              【解决方案6】:

              Hackerrank Day2 解决方案:

              function vowelsAndConsonants(s) {
              //Create Array of vowels
                 const vowels = ["a","e","i","o","u"];
              //Convert String to Array
                 const arr = s.split("");
              //Empty vowels and cons array
                 var vowelsFound = [];
                 var cons = [];
              //Push vowels and cons to their arrays
                 for (var i in arr) {
                   if (vowels.includes(arr[i])) {
                      vowelsFound.push(arr[i]);
                      } else {
                          cons.push(arr[i]);
                      }
                 }
              //ConsoleLog so that they in order and cons follows vowels on new lines
                 console.log(vowelsFound.join('\n') + '\n' + cons.join('\n'))
              }
              //Test, Exclude in copy
              vowelsAndConsonants(javascriptloops); 
              

              【讨论】:

              • “简洁是可以接受的,但更全面的解释更好。”尝试解释您的解决方案以使其更容易被接受。
              【解决方案7】:

              我们可以简单地使用正则表达式来匹配元音和辅音,然后打印它们。

              下面是工作代码sn-p:

                      function vowelsAndConsonants(s) {
                          var vw =s.match(/[aeiouAEIOU]+?/g); //regular expression to match vowels
                          var con=s.match(/[^aeiouAEIOU]+?/g); //regular expression to not match vowels, ie. to match consonants
                          printOnConsole(vw); //print vowels
                          printOnConsole(con); //print consonants
                     }
              
                    //function to print values on console.
                     function printOnConsole(arrPrint){
                       for(var i=0;i<arrPrint.length;i++){
                          console.log(arrPrint[i]);
                        } 
                     }
              

              【讨论】:

                【解决方案8】:

                所以这是我使用的最终代码。感谢 Dash 和峰会的帮助。我结合了他们的两个代码。

                // This is the function with the parameter which will have the input.
                
                    function vowelsAndConsonants(s) {
                
                // This lists, all the vowels. Since I know the input is all lowercase, there is no need for uppercase. A lowercase method could also be used.
                
                    const vowels = ['a', 'e', 'i', 'o', 'u'];
                
                // The input is split up to avoid printing the entire string, and is stored in a variable.
                
                    var letters = s.split('');
                
                // An array to hold the vowels is created.
                
                    var vowelsFound = [];
                
                // An array to hold the consonants is created.
                
                    var consonantsFound = [];
                
                
                // Loops through all the split up characters held in the letters variable.
                
                    for (var i in letters) {
                
                // If statement tests by using include to see if any of vowels match the i looper.
                
                        if (vowels.includes(letters[i])) {
                
                //If any vowels do match, then they get added to the end of the vowelsFound array,
                

                然后将其向上推,以便可以按照它们出现的顺序打印。

                            vowelsFound.push(letters[i]);
                
                //The same process is used for the consonants.
                
                        } else {
                            consonantsFound.push(letters[i]);
                        }
                    }
                
                //Prints the vowels in their order, on a new line for each character.
                
                    console.log(vowelsFound.join('\n'));
                    console.log(consonantsFound.join('\n'));
                }
                

                【讨论】:

                  【解决方案9】:

                  您可以使用包含来检查给定字符串上的元音数组

                  const vowelsAndconsonants = str => {
                    const vowels=['a','e','i','o','u'];
                    //convert string to array and get rid of non alphabets as we are just interested on consonants and vowel
                    const str_array=str.replace(/[^a-zA-Z]/g, '').split('');
                    //pluck vowels
                    const vowels_final=str_array.filter( a => vowels.includes(a.toLowerCase()));
                    //pluck consonants
                    const consonant_final=str_array.filter( a => !vowels.includes(a.toLowerCase()));
                  //to print any vowels from a word on a new line and then consonant in the order they appear. 
                    return vowels_final.join('\n') + '\n' + consonant_final.join('\n');
                  }
                  
                  console.log(vowelsAndconsonants('tEstOnlY and nothing else'))
                  console.log(vowelsAndconsonants('dry'))
                  console.log(vowelsAndconsonants('I love stackoverflow'))

                  【讨论】:

                  • 所以我必须确保拆分每个字母,否则会打印整个字符串。通过拆分字符串的每个字符,然后对每个字符进行测试,看它是元音还是辅音。
                  【解决方案10】:

                  您的主要问题是您决定在检查每个字母时是否应该打印。结果输出实际上是初始字符串。

                  虽然 sumit 的回答可以解决问题,但我会这样做,因为它要求您只遍历字母一次:

                  const vowelsAndConsonants = (str) => {
                      const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
                      // Check for vowels
                  
                      var letters = str.split('');
                      var vowelsFound = [], consonantsFound = [];
                  
                      for (var i in letters) {
                          if (vowels.includes(letters[i])) {
                              vowelsFound.push(letters[i]);
                          } else {
                              consonantsFound.push(letters[i]);
                          }
                      }
                      
                      console.log("Vowels:", vowelsFound.join(""));
                      console.log("Consonants:", consonantsFound.join(""));    
                  }
                  
                  var str = "ThisIsATest";
                  vowelsAndConsonants(str);

                  【讨论】:

                  • 好的,当输入一个字符串时。 Var letters = str.split,创建一个变量,其中字符串的所有字符都被拆分以避免只打印整个字符串。 var vowelsFound = [], consonantsFound = [];创建两个单独的数组来存储每个字符。 For 循环是我卡住的地方。能否解释一下为什么将 Push 用于 vowelsFound 数组背后的想法?
                  • 我认为 Push 方法将字符添加到末尾,因此当 Console.log 打印时,它会以所需的特定顺序显示。很酷的想法。
                  • 没错,使用push,你不用担心你在结果数组的哪个索引下添加值,因为它总是最后一个!
                  猜你喜欢
                  • 1970-01-01
                  • 2016-11-23
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2017-04-29
                  • 1970-01-01
                  相关资源
                  最近更新 更多