过滤字符串数组,只保留以元音开头的字符串

Filter array of strings, keeping only ones starting with vowels

我意识到我已经过度设计了这个,但由于我刚开始使用 JS,我想不出如何将它压缩成不完全荒谬的东西。我知道我可能会在这里踢自己,但有人可以为我重构这个吗?

目的是根据提供的数组创建一个新数组,该数组仅包含以元音开头的字符串。它还需要不区分大小写。

let results = []

for (let i = 0; i < strings.length; i++) {
  if ((strings[i].startsWith('a')) || (strings[i].startsWith('A')) || (strings[i].startsWith('e')) || (strings[i].startsWith('E')) || (strings[i].startsWith('i')) || (strings[i].startsWith('I')) || (strings[i].startsWith('o')) || (strings[i].startsWith('O')) || (strings[i].startsWith('u')) || (strings[i].startsWith('U'))) {
    results.push(strings[i])
  }
}

return results

我会使用 Array#filter and a regular expression:

let rex = /^[aeiou]/i;
let results = strings.filter(str => rex.test(str));

/^[aeiou]/i 说 "At the beginning of the string (^), match a, e, i, o, or u, case-insensitive (the i flag)."

实例:

let strings = [
  "I'll match",
  "But I won't",
  "And I will",
  "This is another one that won't",
  "Useful match here"
];
let rex = /^[aeiou]/i;
let results = strings.filter(str => rex.test(str));

console.log(results);

您可以为此使用一个 RegExp and Array.prototype.filter()

console.log([
  'Foo',
  'Bar',
  'Abc',
  'Lorem',
  'Ipsum'
].filter(str => /^[aeiou]/i.test(str)));

Array.prototype.filter() returns 一个新数组,其中包含所有传递(return 真值)谓词的元素。

RegExp.prototype.test() returns true 如果 RegExp 在您传入的字符串上找到匹配项。

那么,/^[aeiou]/i表示:

  • ^ 匹配字符串的开头。
  • [aeiou] 匹配方括号内的任何字符,一次。
  • i 是不区分大小写的修饰符。

其他答案很好,但请考虑下面显示的这种方法。 如果你刚接触 JS,它肯定会帮助你理解 JS 的基石,比如它的数组方法。

  • map() 方法创建一个新数组,其中包含对调用数组中的每个元素调用提供的函数的结果。

var new_array = arr.map(function callback(currentValue, index, array {
      // Return element for new_array
    }, thisArg)

尝试使用像 https://repl.it/ 这样的 REPL 网站来查看这些方法的作用...

以下是我建议的答案...

function onlyVowels(array) {
// For every element (word) in array we will...
  return array.map((element) => {
    //  ...convert the word to an array with only characters...
    return (element.split('').map((char) => {
      // ...and map will only return those matching the regex expression
      // (a || e || i || o || u)
      // parameter /i makes it case insensitive
      // parameter /g makes it global so it does not return after 
      // finding first match or "only one"
      return char.match(/[aeiou]/ig)
    // After getting an array with only the vowels the join function
    // converts it to a string, thus returning the desired value
    })).join('')
  })
};

function test() {
  var input = ['average', 'exceptional', 'amazing'];
  var expected = ['aeae', 'eeioa', 'aai']
  var actual = onlyVowels(input)

  console.log(expected);
  console.log(actual);
};

test()