【问题标题】:Code for printing vowels and consonants separately not working分别打印元音和辅音的代码不起作用
【发布时间】:2020-04-18 06:13:59
【问题描述】:

输入一个字符串。然后执行:: 每个字母都打印在一个新行上。 然后元音按照它们在 中出现的顺序打印。 然后辅音按照它们出现的顺序打印

示例输入

javascriptloops

样本输出

a
a
i
o
o
j
v
s
c
r
p
t
l
p
s

这就是我所做的

let a = [];
let b = [];
vowelsAndConsonants("javascriptloops");

function vowelsAndConsonants(s) {
  let i;
  let k = 0,
    j = 0;
  s.trim();
  s.toLowerCase();
  for (i = 0; i <= s.length; i++) {
    if (s.charAt(i) === "a" || s.charAt(i) === "e" || s.charAt(i) === "i" || s.charAt(i) === "o" || s.charAt(i) === "u") {
      a[k] = s.charAt(i);
      k++;
    } else {
      b[j] = s.charAt(j);
      j++;
    }
  }

}

for (let i = 0; i <= a.length; i++) {
  console.log(a[i]);
}
for (let i = 0; i <= b.length; i++) {
  console.log(b[i]);
}

【问题讨论】:

  • b[j] = s.charAt(j); 应该是b[j] = s.charAt(i);
  • 你有什么问题?

标签: javascript arrays data-structures


【解决方案1】:

更新了代码。

无需保留和更新k & j

我所做的是,如果元音存在,则将其推送到数组a,否则将辅音推送到b

还请记住,数组从索引 0 开始,因此您必须将条件提及为 &lt; array.length 而不是 &lt;= array.length

let a = [];
let b = [];
vowelsAndConsonants("javascriptloops");

function vowelsAndConsonants(s) {
  s.trim();
  s.toLowerCase();
  for (i = 0; i < s.length; i++) {
    if (s.charAt(i) === "a" || s.charAt(i) === "e" || s.charAt(i) === "i" || s.charAt(i) === "o" || s.charAt(i) === "u") {
      a.push(s.charAt(i));
    } else {
      b.push(s.charAt(i));
    }
  }

}

for (let i = 0; i < a.length; i++) {
  console.log(a[i]);
}
for (let i = 0; i < b.length; i++) {
  console.log(b[i]);
}

【讨论】:

    【解决方案2】:

    最好的方法是使用正则表达式来匹配元音和辅音,然后打印它们。

    下面是工作代码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]);
              } 
           }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多