如何根据情况增加属性值

时间:2019-05-28 05:58:49

标签: javascript

使用字符串作为输入,要求您在字符串中找到元音,并在属性中添加每个元音的出现。因此,如果我们输入“ Hello”,则属性将为(下方)。使用reduce方法解决此问题的最佳方法是什么?

mainactivity

2 个答案:

答案 0 :(得分:-1)

一种实现方式:

split字符串到字符数组,并对其进行迭代,并像执行操作一样建立结果状态:

const str = "Hello World!";
const chars = str.toLowerCase().split("");

const vowels = ['a', 'e', 'i', 'o', 'u']
const state = {a: 0, e: 0, i: 0, o: 0,  u: 0, total: 0};

const result = chars.reduce((a, char) => {
  if (vowels.includes(char)) {
    a[char] += 1;
    a.total += 1;
  }
  return a;
}, state);

console.log(result);

答案 1 :(得分:-1)

您可以这样做

const string = "The quick brown fox jumps over the lazy dog";
const vowels = ["a","e","i","o","u"];
const vowelsCounts = {"a":0,
"e":0,
"i":0,
"o":0,
"u":0,
"total":0 
};

for(let i=0; i < string.length; i++){
  let character = string[i].toLowerCase();
  if(vowels.includes(character)){
    vowelsCounts[character]++;
    vowelsCounts.total++;
  }
}

console.log(vowelsCounts);