Fuse.js 在字符串数组中搜索

Luk*_*vek 7 javascript fuse.js

我试图在我的应用程序中实现 fuse.js ,其中我有没有任何键的字符串数组。

['Kelly', 'Creed', 'Stanley', 'Oscar', 'Michael', 'Jim', 'Darryl', 'Phyllis', 'Pam', 'Dwight', 'Angela', 'Andy', 'William', 'Ryan', 'Toby', 'Bob']
Run Code Online (Sandbox Code Playgroud)

当我尝试配置 fuse.js 时,由于未指定密钥,我没有得到任何结果。

var options = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  keys: [
    "title",
    "author.firstName"
  ]
};
var fuse = new Fuse(list, options); // "list" is the item array
var result = fuse.search("");
Run Code Online (Sandbox Code Playgroud)

是否可以对普通数组执行模糊搜索,还是需要将所有内容都转换为对象?

Eri*_*ner 4

可以对字符串数组进行搜索。您不需要指定keys在选项对象中指定属性。

这是一个例子:

const list = ['Kelly', 'Creed', 'Stanley'];

// your options can be anything you want, but don't include
// the keys property
let options = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  // don't include the keys property
};

const fuse = new Fuse(list, options);

let result = fuse.search('Kelly');
// result will be:
// {"item":"Kelly","refIndex":0}
// here, refIndex is the index of the element in list
Run Code Online (Sandbox Code Playgroud)