企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] > [github](https://github.com/krisk/fuse/) > [home](https://fusejs.io/) ## 安装 `npm install fuse.js` ## 概述 Fuse.js 是一个轻量级的模糊搜索,在 JavaScript 中,零依赖。 ### 浏览器兼容性 Fuse.js 支持所有[符合 ES5 的](http://kangax.github.io/compat-table/es5/)浏览器(不支持 IE8 及以下版本) ## 完整 demo ``` // html <input type="text" id="search"> <ul id="content"> </ul> // js <script src="https://cdn.bootcss.com/fuse.js/3.4.5/fuse.min.js"></script> <script> var list=[ { title: "Old Man's War", author: { firstName: "John", lastName: "Scalzi" } }, { title: "The Lock Artist", author: { firstName: "Steve", lastName: "Hamilton" } }, ]; var options = { shouldSort: true, threshold: 0.1, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 3, keys: [ "title", "author.firstName" ] }; var fuse = new Fuse(list, options); // "list" is the item array var content = document.querySelector("#content"); document.querySelector("#search").addEventListener("input",function (item) { var result = fuse.search(item.target.value); console.log(result); var html =""; result.forEach(function (item) { html+=`<li>title : ${item.title} | firstName : ${item.author.firstName} | lastName : ${item.author.lastName} </li>`; }) content.innerHTML=html; }) </script> ``` ## 官方 demo ### 按ID搜索 搜索结果只返回 id 指定的值 ``` var books = [{ 'ISBN': 'A', 'title': "Old Man's War", 'author': 'John Scalzi' }, { 'ISBN': 'B', 'title': 'The Lock Artist', 'author': 'Steve Hamilton' }] var options = { keys: ['title', 'author'], id: 'ISBN' } var fuse = new Fuse(books, options) fuse.search('old') /**[ "A" ]*/ ``` ### 加权搜索 加权影响结果排名 ``` var books = [{ title: "Old Man's War fiction", author: 'John X', tags: ['war'] }, { title: 'Right Ho Jeeves', author: 'P.D. Mans', tags: ['fiction', 'war'] }] var options = { keys: [{ name: 'title', weight: 0.3 }, { name: 'author', weight: 0.7 }] }; var fuse = new Fuse(books, options) fuse.search('Man') /** [{ "title": "Right Ho Jeeves", "author": "P.D. Mans", "tags": ["fiction", "war"] }, { "title": "Old Man's War fiction", "author": "John X", "tags": ["war"] }] */ ```` ### 在字符串数组中搜索 数组中的值可以进行搜索 ``` var books = [{ 'title': "Old Man's War", 'author': 'John Scalzi', 'tags': ['fiction'] }, { 'title': 'The Lock Artist', 'author': 'Steve', 'tags': ['thriller'] }] var options = { keys: ['author', 'tags'] }; var fuse = new Fuse(books, options) fuse.search('tion') /**[{ "title": "Old Man's War", "author": "John Scalzi", "tags": ["fiction"] }]*/ ```