我目前正在开发一个基本的披萨外卖应用程序。因此,您单击所需的披萨,它就会添加到列表中,该列表对结果进行分组。
所以它应该显示:
玛格丽塔披萨 2x 萨拉米披萨 1x
我想过做一个像 Map<Pizza, number>
这样的 map 其中 Pizza 是我的对象,number 是数量。
但是这感觉不对。我也无法用 ngFor 迭代它。
那么创建一个对象不是很容易吗,比如: { "pizza": Pizza, "amount": 2} 并将其放入数组中?
最佳答案
这很大程度上取决于您的用例。
So wouldn't it just be easy to create an object, like: { "pizza": Pizza, "amount": 2} and put this in an array?
如果您想从中获取特定项目并且不知道索引,则必须搜索该数组。
Map
的好处是您可以快速查找,并且可以使用 Object
作为键,而不仅仅是 String
。
class Pizza {};
// Using Map
const orderMap = new Map();
const margaritaPizza = new Pizza();
const salamePizza = new Pizza();
orderMap.set(margaritaPizza, 2);
orderMap.set(salamePizza, 1);
console.log(`Margarita ammount: ${orderMap.get(margaritaPizza)}`);
console.log(`Salame ammount: ${orderMap.get(salamePizza)}`);
// Using Array
const orderArr = [];
orderArr.push({
pizza: "margaritaPizza",
ammount: 2
});
orderArr.push({
pizza: "salamePizza",
ammount: 1
});
console.log(`Margarita ammount: ${orderArr.find(el => el.pizza === "margaritaPizza").ammount}`);
console.log(`Salame ammount: ${orderArr.find(el => el.pizza === "salamePizza").ammount}`);
此外,您还说:
I thought about doing a Map like Map where Pizza is my object and the number is the amount.
However this doesnt feel right. Also I can't iterate with ngFor through it.
Map
实现 @@iterator
并且可以使用 Array.from()
转换为普通的 Array
。
关于javascript - Typescript 使用 Map 或 Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51482880/