简体   繁体   中英

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}. ;

  • 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:

  • Using keydown eventlistener
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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