字符串 indexOf 总是 return -1

String indexOf always return -1

我在尝试使用 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;
});

当我将关键字作为字母键入时,它总是 return 空数组(即 indexOf return -1)。如果我输入数字,例如 1 或 10 或 100 或 00,我会得到正确的结果。

为什么?

如有任何帮助,我们将不胜感激。谢谢

@trinvh 根据您评论中的输出,您在中间有一个尾随 space 在 haystack 中搜索 needle 时,如果 needle 得到尾随 space , 将无法匹配(因为我们在这里处理的是不包含 spaces 的 slug)

/* according to your comment: */
console.log('-' + itemNameSlug + '-', '-' + keywordSlug + '-', typeof itemNameSlug, typeof keywordSlug);
/* gives: -product95 - -pro - string string */

那么我会说 是 "pro ",它与 "product95 "

不匹配