搜索框实现模糊查询方法 - js

JavaScript07

搜索框实现模糊查询方法 - js,第1张

日常开发中经常会遇到搜索框查询的例子,需要对数组中的元素进行检索并查询出所需的结果,通过如下方式简单实现了一个小的模糊查询,具体如下:

首先,用到了两个方法

1.对数组通过 filter 的方式遍历查询搜索的 key

2.对遍历出的结果进行字符串的模糊查询 str.indexOf("xxx") != -1

其次,通过如上两种方法的组合从而获得一个类似模糊查询的效果;

最后,具体实现 code 如下:

此次实现搭配使用的是该 Vant Search 组件

UI 部分很简单直接根据 demo 实例集成即可。

以上便是此次分享的全部内容,希望能对大家有所帮助!

var Chinese = new RegExp('[\u4E00-\u9FA5]+') //中文

var Letter = new RegExp('[A-Za-z]+') //字母

      if (Chinese.test(this.systemInput)) {

        //中文搜索

        this.showOpList = this.List.filter(array => {

          if (array.title != undefined) {

            return array.title.indexOf(this.systemInput) >= 0

          }

          return false

        })

      }

if (Letter.test(this.systemInput)) {

        //字母搜索

        this.showOpList = this.List.filter(array => {

          let flag = false

          if (array.letter != undefined) {

            flag = array.letter.indexOf(this.systemInput) >= 0

          }

          if (array.spelling != undefined && !flag) {

            flag = array.spelling.indexOf(this.systemInput) >= 0

          }

          return flag

        })

      }