无法找到如何在输出末尾删除“ undefined”

问题描述

基本上,练习希望我先将字符串的特征排序为元音,然后再将辅音排序

样本输入

javascriptloops

样本输出

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

这是我尝试过的功能

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

  for (let i = 0; i < s.length -1 ; i++) {
    if (s[i] !== "a" && s[i] !== "e" && s[i] !== "i" && s[i] !== "o" && s[i] !== "u") {
      vowel += s[i] + "\n";
    } 
  }
  for (let i = s.length -1; i<= s.length; i++) {
    if (s[i] !== "a" && s[i] !== "e" && s[i] !== "i" && s[i] !== "o" && s[i] !== "u") {
        vowel += s[i] ;
      } 
  }  
  console.log(vowel)
}

vowelsAndConsonants('javascriptloops')输出是:

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

我如何摆脱这种“不确定”?我知道它来自console.log,但他们希望我用它来打印输出。谢谢!

解决方法

评论中已经提供了答案(需要使用<而不是<=,因为str [str.length]是undefined),但是我想提出一个建议针对您的问题的更具可读性的代码:

const vowFirst = (input) => {
    const arr = input.split(''); // Create an array from the string,to loop it easier
    const vowels = ['a','e','i','o','u']; // Also create an array from the chars you want to treat differently

    return [
        ...arr.filter(char => vowels.includes(char)),// get an array of all the chars in the original array that are vowels (in order)
        ...arr.filter(char => !vowels.includes(char)) // get an array of all the chars in the original array that are NOT vowels (in order)
    ].join('\n'); // join the array back to a string (with \n)
}

console.log(vowFirst('javascriptloops'));

我建议您阅读Mozilla Devs上的数组函数,因为它们可以使您的代码更具可读性,并且比手动循环或类似循环更容易处理。

此外,我建议您在链接的同一页面上检查JS的基础知识(例如示例中使用的Spread Operator)。