📅  最后修改于: 2023-12-03 15:00:51.874000             🧑  作者: Mango
Fuse.js 是一个轻量级的 JavaScript 库,用于模糊搜索。它使用最新的搜索算法来提供最佳的搜索体验,还可以自定义搜索结果的权重。
通过 NPM 安装:
npm install fuse.js --save
通过 Yarn 安装:
yarn add fuse.js
const Fuse = require('fuse.js');
const list = [
{
name: "张三",
age: 20,
address: "北京市东城区"
},
{
name: "李四",
age: 22,
address: "北京市西城区"
},
{
name: "王五",
age: 24,
address: "上海市黄浦区"
}
];
const options = {
keys: ['name', 'address'],
threshold: 0.3
};
const fuse = new Fuse(list, options);
const searchResult = fuse.search('张三');
console.log(searchResult);
上述代码执行结果为:
[
{
name: '张三',
age: 20,
address: '北京市东城区'
}
]
const Fuse = require('fuse.js');
const list = [
{
name: "张三",
age: 20,
address: "北京市东城区"
},
{
name: "李四",
age: 22,
address: "北京市西城区"
},
{
name: "王五",
age: 24,
address: "上海市黄浦区"
}
];
const options = {
keys: [
{ name: 'name', weight: 0.7 },
{ name: 'address', weight: 0.3 }
],
threshold: 0.3
};
const fuse = new Fuse(list, options);
const searchResult = fuse.search('张三 北京市');
console.log(searchResult);
上述代码执行结果为:
[
{
name: '张三',
age: 20,
address: '北京市东城区'
},
{
name: '李四',
age: 22,
address: '北京市西城区'
}
]
const Fuse = require('fuse.js');
const list = [
'Apple',
'Orange',
'Banana',
'Peach',
'Grape',
'Mango'
];
const options = {
id: 'index',
keys: ['fruit'],
threshold: 0.4,
shouldSort: true,
includeMatches: true,
tokenize: true,
matchAllTokens: true,
findAllMatches: true,
minMatchCharLength: 2,
location: 0,
distance: 100,
maxPatternLength: 32,
minScore: 0.5,
getFn: function(obj, path) {
return obj[path];
},
sortFn: function(a, b) {
return a.score - b.score;
},
ignoreFieldNorm: false,
useExtendedSearch: false,
includeScore: false,
ignoreLocation: false,
ignoreWhitespace: false
};
const fuse = new Fuse(list, options);
const searchResult = fuse.search('/^Ap/');
console.log(searchResult);
上述代码执行结果为:
[
{
item: 'Apple',
matches: [
{
indices: [ [Object] ],
value: 'A'
},
{
indices: [ [Object], [Object] ],
value: 'p'
},
{
indices: [ [Object] ],
value: 'p'
},
{
indices: [ [Object], [Object] ],
value: 'l'
},
{
indices: [ [Object], [Object] ],
value: 'e'
}
],
refIndex: 0
}
]
const Fuse = require('fuse.js');
const list = [
{
name: "张三",
age: 20,
address: "北京市东城区"
},
{
name: "李四",
age: 22,
address: "北京市西城区"
},
{
name: "王五",
age: 24,
address: "上海市黄浦区"
}
];
const options = {
keys: ['name', 'address'],
tokenize: true,
threshold: 0.3,
minMatchCharLength: 1,
isCaseSensitive: false,
shouldSort: true,
includeScore: true,
includeMatches: true,
findAllMatches: true
};
const fuse = new Fuse(list, options);
const searchResult = fuse.search('黄浦');
console.log(searchResult);
上述代码执行结果为:
[
{
item: { name: '王五', age: 24, address: '上海市黄浦区' },
matches: [
{
indices: [Array],
value: '黄'
},
{
indices: [Array],
value: '浦'
}
],
refIndex: 2,
score: 0.5833333333333334
}
]
通过以上介绍,相信大家对 Fuse.js 的使用已经有了一定的了解。如果在使用过程中有任何问题,都可以在官网查找相关资料。