我是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);
}
答案 0 :(得分:1)
看起来很不错。我唯一可以建议(并且它是非常小的改进)是在循环之前缓存关联数组的长度,如下所示:
for (var i = 0, len = myObject.length; i < len; i++) {
您还可以移动最后一个if
语句,以检查是否在for
循环之外找不到搜索参数,如下所示:
for (var i = 0, len = myObject.length; i < len; i++) {
if (myObject[i].word == arg) {
document.write(myObject[i].id + " - " + myObject[i].word + " - " + myObject[i].definition + "<br>");
count += 1;
}
if(i == len-1 && count > 0) return;
}
document.write("NOT FOUND!");
如果在结束for
循环之前找到任何搜索参数,则此代码退出搜索功能。这意味着,如果搜索结果为“未找到”,则for
循环之外的任何代码都会运行。
答案 1 :(得分:0)
尝试这种方式:
var myObject = {'ant': {id: 1, word: 'ant', definition: 'an insect with eight legs.'},
'cake' : {id: 2, word: 'cake', definition: 'a food made with flour and sugar.'},
'house' : {id: 3, word: 'house', definition: 'a building where a family lives.'},
};
function search(arg){
var count = 0;
if (myObject[arg] != undefined)
{
document.write(myObject[arg].id + " - " + arg + " - " + myObject[arg].definition + "<br>");
}
else
{
document.write("NOT FOUND!");
}
}
这仅适用于每个单词有一个定义的情况。如果你想拥有更多,并且仍然能够召唤关联数组的力量,你可以将字典变量更改为:
var myObject = {'ant': [{id: 1, word: 'ant', definition: 'an insect with eight legs.'}, {id: 666, word: 'ant', definition: 'progeny of the devil'}],
'cake' : [{id: 2, word: 'cake', definition: 'a food made with flour and sugar.'}],
'house' : [{id: 3, word: 'house', definition: 'a building where a family lives.'}],
};
当然会相应地更改代码
答案 2 :(得分:0)
以下是我的看法:
var i, found = 0;
for (i = 0; i < myArray.length; i++) {
if(myArray[i].word === arg) {
document.write(myArray[i].id + " - " + myArray[i].word + " - " + myArray[i].definition + "<br>");
found++;
}
}
if(found === 0) {
document.write("None found!");
}
或者不是最终的if
,您可以随时写下找到的项目数:
document.write(found.toString() + " items found");