gpt4 book ai didi

javascript - 按提供的输入过滤值

转载 作者:行者123 更新时间:2023-11-30 20:17:20 25 4
gpt4 key购买 nike

当用户提供的输入使用可以是单词或数字(均为字符串)的值过滤列表时,我尝试实现这种情况。

下面都是描述的案例,不知道有没有办法把这三个案例的验证合二为一。非常感谢好的建议:)

Case 1: 1 === 1
Case 2: +1 === +1
Case 3: (+1) ==== (+1)

const form = document.querySelector('input')

form.addEventListener('change', () => {
console.clear()
filterValues()
})

const values = {
first: {code: "1", name: "one"},
second: {code: "2", name: "two"},
third: {code: "3", name: "three"},
four: {code: "4", name: "four"},
five: {code: "5", name: "five"}
}

function filterValues() {
Object.keys(values).forEach(value => {
const code = values[value].code
const name = values[value].name
const input = form.value

const inputMatchesCode = code.indexOf(input.toLocaleLowerCase()) === 0

/* Code case nr 1 */
const inputMatchesName = name.indexOf(input.toLocaleLowerCase()) === 0

/* Code case nr 2 */
const dialingCode = `+${code}`
const inputMatchesDialingCode = dialingCode.indexOf(input.toLocaleLowerCase()) === 0

/* Code case nr 3 */
const fullDialingCode = `(+${code})`
const inputMatchesFullDialingCode = fullDialingCode.indexOf(input.toLocaleLowerCase()) === 0

if (inputMatchesCode || inputMatchesName || inputMatchesDialingCode || inputMatchesFullDialingCode) {
console.log(value)
}
})
}
input {
width: 100%;
border: 1px solid #ccc;
border-radius: 3px;
}
<input type="text" />


最佳答案

如果您正在尝试匹配数字(即:1)并且希望变体与您创建的字符串(即:“(+1)”)匹配 - 而不是尝试匹配所有变体 - 为什么不只需删除辅助字符并仅比较数字 - 即(1 === 1 给出“第一”)。这样您就不必考虑“(”、“+”或“)”字符 - 如果数字本身匹配,您就可以给出预期的结果。

我使用了您的代码,但删除了不同情况背后的备用字符和逻辑。

const form = document.querySelector('input')

form.addEventListener('change', () => {
console.clear()
filterValues()
})

const values = {
first: {code: "1", name: "one"},
second: {code: "2", name: "two"},
third: {code: "3", name: "three"},
four: {code: "4", name: "four"},
five: {code: "5", name: "five"}
}

function filterValues() {
Object.keys(values).forEach(value => {
const code = values[value].code
const name = values[value].name
const input = form.value.replace(/[\(\+\)]/g,'');

const inputMatchesCode = code.indexOf(input.toLocaleLowerCase()) === 0

const inputMatchesName = name.indexOf(input.toLocaleLowerCase()) === 0


if (inputMatchesCode || inputMatchesName) {
console.log(value)
}
})
}
input {
width: 100%;
border: 1px solid #ccc;
border-radius: 3px;
}
<input type="text" />

关于javascript - 按提供的输入过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51804315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com