Javascript超市测试应用程序

时间:2014-02-20 05:28:07

标签: javascript arrays object compare

我用JavaScript创建了这个超市应用程序。它有一个预定义的过道信息。然后,用户为脚本提供3个项目及其所属的类别。如果某个类别与其中一个类别匹配,则该脚本会告诉您项目的位置。

我想知道是否有更强大的高效方式来循环,存储和比较这些数据?我应该在这里使用数组或对象吗?

var safeway = {};
safeway.aisle1 = {
    contents: "fresh produce",
    aisle: "Aisle 1"
};
safeway.aisle2 = {
    contents: "meat and seafood",
    aisle: "Aisle 2"
};
safeway.aisle3 = {
    contents: "dairy",
    aisle: "Aisle 3"
};
safeway.aisle4 = {
    contents: "snacks",
    aisle: "Aisle 4"
};
safeway.aisle5 = {
    contents: "beverages",
    aisle: "Aisle 5"
};
safeway.aisle6 = {
    contents: "frozen foods",
    aisle: "Aisle 6"
};
safeway.aisle7 = {
    contents: "condiments and ingredients",
    aisle: "Aisle 7"
};

li1 = prompt("List Item 1");
li1Category = prompt("What category does this item belong to?");


li2 = prompt("List Item 2");
li2Category = prompt("What category does this item belong to?");


li3 = prompt("List Item 3");
li3Category = prompt("What category does this item belong to?");


var list = {};

list.item1 = {
item: li1,
category: li1Category
};

list.item2 = {
item: li2,
category: li2Category
};

list.item3 = {
item: li3,
category: li3Category
};

var match = function() {
    for(var i in list) {
        for(var x in safeway) {
            if(list[i].category === safeway[x].contents) {
                console.log("The " + list[i].item + " is in " + safeway[x].aisle);
        }
    }

}
};
match();

2 个答案:

答案 0 :(得分:0)

您正在使用“safeway”作为JavaScript对象。 我会说JSON格式是更有效的存储数据的方式。这样您就可以使用jQuery或PHP等轻松解析大量数据。

答案 1 :(得分:0)

您可以使用内容(类别)键和过道值创建safeway对象,以按内容(类别)搜索过道(假设某个类别只能在一个过道中)。

并且,代码中的列表可以是数组。

var safeway = {};

safeway['fresh produce'] = 'Aisle 1';

safeway['meat and seafood'] = 'Aisle 2';

var list = [];

var li = 'beef';
var liCategory = 'meat and seafood';

list.push({
    item: li,
    category: liCategory
});

li = 'some item';
liCategory = 'some category';

list.push({
    item: li,
    category: liCategory
});

function match(items, store) {
    var foundAisle;
    var item;
    for (var i = 0; i < items.length; i++) {
        foundAisle = store[items[i].category];
        item = items[i].item;
        if (foundAisle) {
            console.log("The " + item + " is in " + foundAisle);
        } else {
            console.log("The " + item + " is not found");
        }
    }
};

match(list, safeway);

The beef is in Aisle 2
The some item is not found