在javascript中计算字符串中的元音

Pra*_*abs 3 javascript ecmascript-6

我想使用javascript的reduce()方法获取字符串上元音的数量.下面是代码,问题是在解构acc之后a,e,i,o,u的值是未定义的.

const str = 'I am just a string. I mean nothing serious and I am being used to count the number of vowels I have.';

const strArr = str.split('');



const mapVowels = strArr.reduce(countVowels, {});

function countVowels(acc, char) {
  console.log(char)
  var { a = 0, e = 0, i = 0, o = 0, u = 0 } = acc;
  if (char === "a") {
    return {...acc, a: a + 1};
  }
  if (char === 'i') {
    return { ...acc, i: i + 1}
  }
  if (char === 'e') {
    return { ...acc, e: e + 1}
  }
  if (char === 'o') {
    return { ...acc, o: o + 1}
  }
  if (char === 'u') {
    return { ...acc, u: u + 1}
  }
}
console.log(mapVowels)
Run Code Online (Sandbox Code Playgroud)

我希望mapVowels是一个带有键a,e,i,o,u的对象,并且它们在str中重复它们重复的时间.

Ori*_*ori 5

找到非元音字符时,您不会返回acc.所以,accundefined对下一个迭代,并解构失败.acc即使它不是元音也会返回:

const str = 'I am just a string. I mean nothing serious and I am being used to count the number of vowels I have.';

const strArr = str.split('');

const mapVowels = strArr.reduce(countVowels, {});

function countVowels(acc, char) {
  var { a = 0, e = 0, i = 0, o = 0, u = 0 } = acc;
  
  if (char === "a") {
    return {...acc, a: a + 1};
  }
  if (char === 'i') {
    return { ...acc, i: i + 1}
  }
  if (char === 'e') {
    return { ...acc, e: e + 1}
  }
  if (char === 'o') {
    return { ...acc, o: o + 1}
  }
  if (char === 'u') {
    return { ...acc, u: u + 1}
  }
  
  return acc;
}
console.log(mapVowels)
Run Code Online (Sandbox Code Playgroud)

此外,您可以通过创建一个数组或一串元音,并使用或识别元音来使代码更!String.includes()Array.inclues()

const vowels = 'aieou';

const str = 'I am just a string. I mean nothing serious and I am being used to count the number of vowels I have.';

const strArr = str.split('');

const mapVowels = strArr.reduce(countVowels, {});

function countVowels(acc, char) {
  if(!vowels.includes(char)) return acc;
  
  const { [char]: val = 0 } = acc;
  
  return {...acc, [char]: val + 1};
}

console.log(mapVowels)
Run Code Online (Sandbox Code Playgroud)