Javascript 如何根据材料长度编程计算数量?
我试图计算如果我把一个大尺寸的卷切成多个小尺寸的卷,我可以得到的材料卷的数量 例如,如果我有一个25米的卷轴,我可以把它切成1个15米的卷轴,2个10米的卷轴和5个5米的卷轴。所以我希望我的数量看起来像:Javascript 如何根据材料长度编程计算数量?,javascript,calculation,Javascript,Calculation,我试图计算如果我把一个大尺寸的卷切成多个小尺寸的卷,我可以得到的材料卷的数量 例如,如果我有一个25米的卷轴,我可以把它切成1个15米的卷轴,2个10米的卷轴和5个5米的卷轴。所以我希望我的数量看起来像: 125米 15米 2 10米 5.5米 现在,我也可以有任何其他的现有数量,如1卷25米,1卷15米和1卷5米。然后它看起来像: 125米 215米 3 10米 95m for (let i = 0; i < this.sizes.length; i++) { co
- 125米
- 15米
- 2 10米
- 5.5米
- 125米
- 215米
- 3 10米
- 95m
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; } }
for(设i=0;i
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];
}
}
calculateequanties(){
设数量={};
for(设i=0;i
如果我误解了这个问题,请告诉我哪里出错了。
我假设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
是的,它们是预定义的。让我试试你的答案,我会给你回复的。看起来和我的差不多。