[英]the loop (for) iteration throguh an array
I made a simple program that works as a phone book.我做了一个简单的程序,用作电话簿。 When a user types a name in the input field, the program searches an array of objects containing names and numbers and, if it finds the name, outputs name and phone number.
当用户在输入字段中输入姓名时,程序会搜索包含姓名和号码的对象数组,如果找到姓名,则输出姓名和电话号码。 If the name is not found, it lets the user know.
如果找不到该名称,它会让用户知道。 However, when I type a name the result stays the same 'Name not found', even though the array contains given name.
但是,当我键入名称时,即使数组包含给定名称,结果仍然是“未找到名称”。 Here is the code
这是代码
const phonebook = [
{name : `Adam`, number : `001`},
{name : `Anna`, number : `002`},
]
const input = document.querySelector('input');
const btn = document.querySelector('button');
const para = document.querySelector('p');
btn.addEventListener ('click', function () {
let searchName = input.value.toLowerCase();
input.value = '';
input.focus();
for (let i = 0; i < phonebook.length; i++) {
if (searchName === phonebook[i].name) {
para.textContent = `${phonebook[i].name's number is ${phonebook[i].number}.`;
break;
} else {
para.textContent = `Name not found in phonebook';
}
}
});
para.textContent = ${phonebook[i].name} (<- missing closing bracket) 's number is ${phonebook[i].number}.
para.textContent =
${phonebook[i].name} (<- missing closing bracket) 's number is ${phonebook[i].number}.
; ;
If it's not a specific case where you need for loop and onClick event, I would recommend:如果不是需要循环和 onClick 事件的特定情况,我建议:
btn.addEventListener(keydown, function {
phonebook.filter((x) => x.name === input.value)
if (phonebook.length === 1) {para.textContent = `${phonebook[0].name}'s number is ${phonebook[0].number}`}
else if (phonebook.length === 0) {para.textContent = "not found"};
})
Or something similar.或类似的东西。 So your code are more responsive in terms of giving feedback to the user.
因此,您的代码在向用户提供反馈方面更具响应性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.