JavaScript中检查字符串数组是否包含子字符串
检查 JavaScript 数组是否包含子字符串:
-
在数组上调用
Array.find
方法。 -
使用
includes()
方法检查每个元素是否包含子字符串。 -
Array.find
方法将返回与子字符串匹配的元素的值。
const array = ['hello', 'world'];
const substring = 'hell';
const match = array.find(element => {
if (element.includes(substring)) {
return true;
}
});
console.log(match); // 👉️ hello
if (match !== undefined) {
// array contains substring match
}
我们传递给 Array.find
方法的函数将对数组的每个元素进行调用,直到它返回真值或耗尽数组的元素。
如果函数从不返回真值,则
Array.find
返回未定义。
我们使用 String.includes()
方法检查每个数组元素中是否包含子字符串。
请注意
,String.includes
方法区分大小写。 对于不区分大小写的条件检查,将子字符串和数组元素都转换为小写。
const array = ['hello', 'world'];
const substring = 'HELL';
const match = array.find(element => {
if (element.toLowerCase().includes(substring.toLowerCase())) {
return true;
}
});
console.log(match); // 👉️ hello
if (match !== undefined) {
// array contains substring match
}
使用 findIndex() 检查数组是否包含子字符串
检查 JavaScript 数组是否包含子字符串:
-
在数组上调用
Array.findIndex
方法。 -
使用
includes()
方法检查每个元素是否包含子字符串。 -
Array.findIndex
方法将返回与子字符串匹配的数组元素的索引。
const array = ['hello', 'world'];
const substring = 'hell';
const index = array.findIndex(element => {
if (element.includes(substring)) {
return true;
}
});
console.log(index); // 👉️ 0
if (index !== -1) {
// array contains substring match
}
我们传递给 Array.findIndex
方法的函数会针对数组中的每个元素进行调用,直到它返回真值或遍历整个数组。
如果回调函数的所有调用都返回假值,则 findIndex
返回 -1。
如果必须根据元素在数组中的索引执行操作,则可以使用
findIndex
方法而不是 find 方法,例如 删除一个元素。
使用 filter() 检查数组是否包含子字符串
检查 JavaScript 数组是否包含子字符串:
-
在数组上调用
Array.filter()
方法。 - 检查每个元素是否包含特定的子字符串。
-
Array.filter()
方法返回一个包含所有满足条件的元素的数组。
const array = ['hello', 'world'];
const substring = 'hell';
const matches = array.filter(element => {
if (element.includes(substring)) {
return true;
}
});
console.log(matches); // 👉️ [ 'hello' ]
if (matches.length > 0) {
// array contains substring match
}
无论条件是否满足,我们传递给 Array.filter
方法的函数都会对数组中的每个元素进行调用。
如果数组中有多个满足条件的元素并且您需要它们的所有值,这将很有用。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。