简体   繁体   English

通过数组的循环(for)迭代

[英]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}. ; ;

  • You are missing a losing curlybrackets there.你在那里错过了一个丢失的花括号。
  • You are transforming input to lowercase but you data source includes capital letters.您正在将输入转换为小写,但您的数据源包含大写字母。 Transform both to lower then.然后将两者都转换为更低。

If it's not a specific case where you need for loop and onClick event, I would recommend:如果不是需要循环和 onClick 事件的特定情况,我建议:

  • Using keydown eventlistener使用 keydown 事件监听器
  • Using Filter使用过滤器
    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM