我试图计算如果我将一个更大尺寸的卷切成多个尺寸更小的卷,我可以拥有的卷材数量。
例如,如果我有一个25米的卷筒,我可以将其切成1个15米的卷筒,2个10米的卷筒和5个5米的卷筒。所以我希望我的数量看起来像:
现在,我也可以拥有其他任何一个,例如1卷25米,1卷15米和1卷5米。然后它看起来像:
9 5m
for (let i = 0; i < this.sizes.length; i++) {
const size = this.sizes[i];
for (let j = 0; j < this.cart.items.length; j++) {
const item = this.cart.items[j];
if (item.sizeId === size.id) {
size.quantity -= item.quantity;
}
size.amountOfMaterial = size.quantity * size.length;
}
}
我设置了第一个循环,以根据购物车中已有的内容获取正确数量和数量的材料。我被困在下一部分。
编辑:下面的答案最终让我想出了这个:
calculateQuantities() {
let quantities = {};
for (let i = 0; i < this.sizes.length; i++) {
const size = this.sizes[i];
for (let j = 0; j < this.cart.items.length; j++) {
const item = this.cart.items[j];
if (item.sizeId === size.id) {
size.quantity -= item.quantity;
}
}
size.actualQuantity = size.quantity;
let counter = 0;
for (let j = 0; j < this.sizes.length; j++) {
const otherSize = this.sizes[j];
counter += Math.floor(otherSize.length * otherSize.quantity / size.length)
}
console.log(`${counter} ${size.length}m`);
quantities[size.length] = counter;
}
for (let i = 0; i < this.sizes.length; i++) {
this.sizes[i].quantity = quantities[this.sizes[i].length];
}
}
答案 0 :(得分:0)
如果我误解了这个问题,请告诉我出错的地方。 我假设25,15,10和5是预定义的。它是否正确?我没有在你的问题中看到这个。
// Defined lengths
const lengths = [25, 15, 10, 5];
// Some example cart corresponding to how many of each length customer has (this is from your example)
const cart = {25: 1, 15: 1, 5: 1}
for (let length of lengths) {
//Check for each length in lengths array
let counter = 0;
for (let item in cart) {
// Add the counter if there is enough in cart
counter += Math.floor(item * cart[item] / length);
}
// I am console logging like you showed, but you can do whatever
console.log(`${counter} ${length}m`)
}
输出:
1 25m
2 15m
3 10m
9 5m