I’m new to JavaScript and would like some constructive criticism regarding a code snippet. This example searches an associative array using a value input by the user. Is there a better way to approach this problem; what would be a more elegant solution while still using an associative array? Thanks.
var myObject = [
{id: 1, word: 'ant', definition: 'an insect with eight legs.'},
{id: 2, word: 'cake', definition: 'a food made with flour and sugar.'},
{id: 3, word: 'house', definition: 'a building where a family lives.'},
];
function search(arg){
var count = 0;
for (var i = 0; i <= myObject.length; i++) {
if (myObject[i].word == arg) {
document.write(myObject[i].id + " - " + myObject[i].word + " - " +
myObject[i].definition + "<br>");
count += 1;
}
else {
if (count != 1 &&
myObject[i].word != arg &&
i == myObject.length - 1) {
document.write("NOT FOUND!");
}
}
}
}
var arg = prompt("Search For An Entry");
if (arg != null && arg.length != 0) {
search(arg);
}
Looks pretty good. The only thing I could suggest (and it’s a very small improvement) would be to cache the length of your associative array before looping over it, like this:
You could also move that last
ifstatement to check if the search parameter hasn’t been found outside of theforloop, like this:This code exits the search function if it’s found any of the search params before it ends the
forloop. This means that any code exited outside theforloop only runs if the search results in “not found”.