实习04

项目:好未来 AI 开放平台官网(https://ai.100tal.com/)

负责:开放能力导航栏模糊搜索

触发开能力下拉框之后,实习一个对三级菜单的模糊搜索

效果图

android

问题/难点:

(1)纯前端实现模糊搜索
(2)利用防抖包裹输入框 changeValue 的函数

实现:

问题(1)
1、利用递归将整个导航栏 json 文件便利,将所有三级标题 push 到一个数组中
1
2
3
4
5
6
7
8
9
10
11
12
13
const list = navigatorData.ability.list
let middle = []

const initAbilityData = (data) => {
Object.keys(data).forEach((key) => {
if (data[key].children) {
middle.push(initAbilityData(data[key].children))
} else {
middle.push(data[key])
}
})
}
initAbilityData(list)
2、将输入框的 value 分割成字符串数组以便后续使用
1
2
3
// 例如:输入的value为 '语音'
// 分割成数组就为['语','音']
let abilityValue = e.target.value.split('')
3、建立匹配度并根据匹配度排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const matchDegree = (abilityData, abilityValue) => {
let middleData = abilityData
for (let i = 0; i < middleData.length; i++) {
// 建立匹配度,初始化为0
middleData[i].matchDegree = 0
// 检测匹配度
for (let k = 0; k < abilityValue.length; k++) {
// 利用indexOf,记录每个字符在testName中出现的个数,并记录到匹配度
let index = middleData[i].label.indexOf(abilityValue[k])
while (index != -1) {
middleData[i].matchDegree += 1
index = middleData[i].label.indexOf(abilityValue[k], index + 1)
}
}
}
// 根据匹配度排序
middleData.sort((a, b) => {
return b.matchDegree - a.matchDegree
})
let realData = middleData.filter((item) => {
return item.matchDegree !== 0
})
setAbilitySearchData(realData)
}
问题(2)

防抖

1
2
3
4
5
6
7
8
9
10
// 防抖 如果短时间内大量触发同一事件,只会执行一次函数
function debounce(fn, delay) {
let timer = null //借助闭包
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(fn, delay) // 简化写法
}
}

节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 节流: 减少一段时间的触发频率
function throttle(fn, delay) {
let valid = true
return function () {
if (!valid) {
//休息时间 暂不接客
return false
}
// 工作时间,执行函数并且在间隔期内把状态位设为无效
valid = false
setTimeout(() => {
fn()
valid = true
}, delay)
}
}

实习04
http://example.com/2023/03/14/internship04/
Author
John Doe
Posted on
March 14, 2023
Licensed under