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
方法的函数都会对数组中的每个元素进行调用。
如果数组中有多个满足条件的元素并且您需要它们的所有值,这将很有用。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。