有一个固定需求量耗料,有一个数组对象,按照数组第一顺位中的数据耗料,不够的情况下消耗第二顺位,直到达到固定需求量耗料,并且生成一个新的耗料的数组对象数据。如何用js逻辑实现
时间: 2024-11-24 09:40:59 浏览: 43
在JavaScript中,你可以创建一个函数来处理这个需求。首先,假设你有两个数组,一个是原料列表`ingredients`,另一个是固定的需求量`demand`。下面是一个简单的步骤来实现:
```javascript
function consumeIngredients(ingredients, demand) {
let consumedArray = []; // 存放已消耗的原料
let remainingDemand = demand; // 当前剩余需求
for (let i = 0; i < ingredients.length; i++) { // 遍历原料列表
if (remainingDemand <= 0) { // 如果剩余需求已满,跳出循环
break;
}
const currentIngredient = ingredients[i]; // 获取当前原料
const ingredientQuantity = Math.min(currentIngredient, remainingDemand); // 取消耗量不超过剩余需求的部分
consumedArray.push(ingredientQuantity); // 添加到已消耗数组
remainingDemand -= ingredientQuantity; // 减少剩余需求
}
// 返回消耗后的原料数组和剩余未消耗的原料
return {
consumed: consumedArray,
remaining: ingredients.filter((ingredient, index) => index >= consumedArray.findIndex(item => item === ingredient)), // 去掉已消耗的原料
};
}
// 示例
const ingredients = [10, 20, 30]; // 比如原料总量
const demand = 25; // 固定需求量
const result = consumeIngredients(ingredients, demand);
console.log('消耗的原料:', result.consumed);
console.log('剩余的原料:', result.remaining);
```
这个函数会返回两个值:一是已经消耗的原料数组,二是剩余的原料数组。当满足需求后,它会停止消耗并保持剩余的原料。
阅读全文
相关推荐



















