【发布时间】:2021-03-08 19:46:34
【问题描述】:
如果关键字是子字符串,我无法弄清楚为什么此函数不返回结果。
const string = 'cake';
const substring = 'cak';
console.log(string.includes(substring));
// returns true
但是当我在这里尝试做类似的事情时,我没有得到我期望的结果。
function filterByKeyword(array, keyword) {
return array.filter((x) =>
x.keywords
.map(function(x) {
return x.toLowerCase();
})
.includes(keyword.toLowerCase())
);
};
const array = [{
"id": 1014,
"keywords": [
"Sesame Street",
"Cake",
"Party",
"Birthday"
]
},
{
"id": 1015,
"keywords": [
"Sesame Street",
"Party",
"Birthday"
]
}
];
console.log(filterByKeyword(array, 'cak'))
// returns []
console.log(filterByKeyword(array, 'cake'))
// returns an array with the correct object
我做错了什么?
【问题讨论】:
-
数组包含 !== 字符串包含
["sesame street", "cake", "party", "birthday"].includes("cak") -
要跟进@epascarello 所说的内容,您需要检查每个 字符串
.includes()是否是子字符串,而不是整个 数组。
标签: javascript arrays