📜  开玩笑检查字符串数组 - Javascript (1)

📅  最后修改于: 2023-12-03 15:09:48.363000             🧑  作者: Mango

开玩笑检查字符串数组 - Javascript

在编写处理大量数据或用户输入的代码时,经常需要检查字符串数组中的每个字符串是否符合特定的条件。本文将介绍如何使用Javascript编写一个开玩笑检查字符串数组的函数。我们将使用以下流程:

  1. 定义字符串数组
  2. 遍历数组并检查每个字符串是否符合特定的条件
  3. 将符合条件的字符串存储在另一个数组中
  4. 返回该数组
定义字符串数组

我们将使用以下字符串数组:

const jokes = ["Why was the math book sad? Because it had too many problems.",
               "I'm reading a book about anti-gravity. It's impossible to put down!",
               "Why did the tomato turn red? Because it saw the salad dressing!",
               "What do you call an alligator in a vest? An investigator.",
               "Why don't scientists trust atoms? Because they make up everything."]
遍历数组并检查每个字符串是否符合特定的条件

我们想要检查每个字符串是否包含单词'why'和'because',如果包含这两个单词,则认为是开玩笑的。

在这个例子中,我们将使用forEach方法遍历数组,并使用includes方法检查每个字符串是否包含'why'和'because'。

const funnyJokes = []
jokes.forEach(joke => {
  if (joke.includes('why') && joke.includes('because')) {
    funnyJokes.push(joke)
  }
})
将符合条件的字符串存储在另一个数组中

我们创建一个空数组funnyJokes来存储符合条件的字符串。

如果一个字符串符合条件,则将其存储在funnyJokes数组中。

返回该数组

最后,我们使用return语句将funnyJokes数组返回。

完整代码如下:

const jokes = ["Why was the math book sad? Because it had too many problems.",
               "I'm reading a book about anti-gravity. It's impossible to put down!",
               "Why did the tomato turn red? Because it saw the salad dressing!",
               "What do you call an alligator in a vest? An investigator.",
               "Why don't scientists trust atoms? Because they make up everything."]

function findFunnyJokes(jokes) {
  const funnyJokes = []
  jokes.forEach(joke => {
    if (joke.includes('why') && joke.includes('because')) {
      funnyJokes.push(joke)
    }
  })
  return funnyJokes
}

console.log(findFunnyJokes(jokes)) // ["Why was the math book sad? Because it had too many problems.", "Why did the tomato turn red? Because it saw the salad dressing!", "Why don't scientists trust atoms? Because they make up everything."]

现在我们已经成功地创建了一个函数,用于检查字符串数组中的开玩笑。这个例子只是一个入门级别的示例,您可以根据具体需求自由发挥。