📅  最后修改于: 2023-12-03 15:09:48.363000             🧑  作者: Mango
在编写处理大量数据或用户输入的代码时,经常需要检查字符串数组中的每个字符串是否符合特定的条件。本文将介绍如何使用Javascript编写一个开玩笑检查字符串数组的函数。我们将使用以下流程:
我们将使用以下字符串数组:
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."]
现在我们已经成功地创建了一个函数,用于检查字符串数组中的开玩笑。这个例子只是一个入门级别的示例,您可以根据具体需求自由发挥。