可以使用以下代码实现:

var giftItems = [
  { name: 'item1', weight: 2 },
  { name: 'item2', weight: 3 },
  { name: 'item3', weight: 1 },
  { name: 'item4', weight: 4 },
  { name: 'item5', weight: 2 }
];

var totalGiftCount = 10; // 总赠送件数

var selectedGiftCount = 0; // 已选赠品数量
var selectedGiftItems = []; // 已选赠品列表

giftItems.sort(function(a, b) {
  return a.weight - b.weight;
}); // 按照weight升序排序

for (var i = 0; i < giftItems.length; i++) {
  if (selectedGiftCount >= totalGiftCount) {
    break; // 已选满总赠送件数,退出循环
  }

  selectedGiftItems.push(giftItems[i]); // 将当前商品加入已选赠品列表
  selectedGiftCount += giftItems[i].weight; // 更新已选赠品数量
}

console.log(selectedGiftItems); // 输出已选赠品列表

上述代码中,首先将giftItems数组按照weight升序排序,然后逐一遍历数组,将商品加入已选赠品列表并更新已选赠品数量,直到已选满总赠送件数或者遍历完整个数组。最后输出已选赠品列表

js中数组对象按照weight顺序逐一勾选勾选至选满总赠送件;目前默认勾选的商品没有选满总赠送件数

原文地址: http://www.cveoy.top/t/topic/eB4N 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录