我在尝试使用Array.filter方法过滤数组时陷入困境。
请查看我的代码:
$scope.products = CachedData.Products.filter(function (item) {
var itemNameSlug = Helpers.slug(item.Name); // eg: product100
var keywordSlug = Helpers.slug($scope.keyword); // eg: p, pr, pro, duct etc...
var result = itemNameSlug.indexOf(keywordSlug);
console.log(result); // always -1
return result > -1;
});
当我输入关键字作为字母时,它总是返回空数组(indexOf返回-1)。如果我输入数字,例如1或10或100或00,我得到了正确的结果。
为什么?
任何帮助将不胜感激。感谢
答案 0 :(得分:0)
@trinvh根据你评论中的输出,你的中间有一个尾随空格 当在 haystack 中搜索 needle 时,如果 needle 获得一个尾随空格,则无法匹配(因为我们在这里处理)与slugs,不包含空格)
/* according to your comment: */
console.log('-' + itemNameSlug + '-', '-' + keywordSlug + '-', typeof itemNameSlug, typeof keywordSlug);
/* gives: -product95 - -pro - string string */
然后我会说针是“pro”,这与“product95”不匹配