您可以使用循环遍历对象中的数组,并使用字符串的includes方法来检查数组中的每个字符串是否包含特定文本。然后,您可以使用一个变量来计算包含特定文本的字符串的数量。
以下是一个示例代码:
function countStrings(obj, searchText) {
let count = 0;
// 遍历对象的属性
for (let key in obj) {
if (Array.isArray(obj[key])) {
// 遍历数组中的每个元素
obj[key].forEach(str => {
// 检查字符串是否包含特定文本
if (str.includes(searchText)) {
count++;
}
});
}
}
return count;
}
// 示例对象
const obj = {
arr1: ['hello', 'world'],
arr2: ['foo', 'bar'],
arr3: ['hello', 'baz', 'world'],
};
// 调用函数
const result = countStrings(obj, 'hello');
console.log(result); // 输出2,因为obj对象中的两个数组都包含了'hello'文本
在上面的示例代码中,countStrings
函数接受一个对象和一个搜索文本作为参数。它使用for...in
循环遍历对象的属性,然后使用Array.isArray
方法检查属性值是否为数组。如果是数组,它使用forEach
方法遍历数组中的每个元素,并使用includes
方法检查字符串是否包含搜索文本。如果是,则增加计数器count
的值。
最后,函数返回计数器的值,即包含特定文本的字符串的数量。在示例代码中,我们使用了一个示例对象obj
和调用函数countStrings(obj, 'hello')
来演示函数的使用。