当用户提供的输入使用值可以是单词或数字(都是字符串)的值过滤列表时,我尝试实现这种情况。
下面都是描述的案例,但是我想知道是否有一种方法可以将所有三个案例验证合并为一个。很好的建议深表感谢:)
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" />
答案 0 :(得分:1)
如果您尝试匹配数字(即: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" />