代码示例:
function checkElements(text) {
if (text.includes("apple") && text.includes("pear")) {
return "both";
} else if (text.includes("apple")) {
return "apple";
} else if (text.includes("pear")) {
return "pear";
} else {
return "neither";
}
}
console.log(checkElements("I like apple and pear")); //输出"both"
console.log(checkElements("I only like apple")); //输出"apple"
console.log(checkElements("I only like pear")); //输出"pear"
console.log(checkElements("I don't like either")); //输出"neither"
对于上面的例子,函数接受输入的文本并检查该文本是否包含"apple"或"pear"。如果同时包含"apple"和"pear",函数返回字符串"both";如果只包含"apple",函数返回字符串"apple";如果只包含"pear",函数返回字符串"pear";如果既不包含"apple"也不包含"pear",函数将返回字符串"neither"。
该函数使用JS中的字符串方法includes()
来检查输入文本中是否包含指定的元素。如果包含该元素,includes()
方法将返回true
,否则返回false
。此外,该函数使用条件语句if...else if...else
来判断是否包含所有指定元素,并返回相应的输出值。示例代码中的console.log()
语句用于在控制台输出每个输入字符串的输出值。