我用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();
您可以使用内容(类别)键和通道值使 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
你正在使用"safeway"作为JavaScript对象。我会说JSON格式是存储数据的更有效的方式。这样您就可以使用 jQuery 或 PHP 等轻松解析您的大量数据。