0

我是 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);
} 
4

3 回答 3

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只有在搜索结果为“未找到”时,退出循环的任何代码才会运行。

于 2012-05-14T14:07:59.857 回答
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.'}],
        };

当然也相应地更改代码

于 2012-05-14T14:21:29.670 回答
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!");
}

或者代替 final if,你可以总是写找到的项目的数量:

document.write(found.toString() + " items found");
于 2012-05-15T00:33:46.120 回答