我是 JavaScript 新手,希望对代码片段提出一些建设性的批评。此示例使用用户输入的值搜索关联数组。有没有更好的方法来解决这个问题?在仍然使用关联数组的同时,什么是更优雅的解决方案?谢谢。
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);
}