[TOC] > [github](https://github.com/krisk/fuse/) > [home](https://fusejs.io/) ## 安装 `npm install fuse.js` ## 完整 demo ``` 搜索 <input type="text" id="search"> <ul id="content"> </ul> <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"] }]*/ ```