JavaScript循环,从总计中减去直到没有任何东西

时间:2013-08-07 06:46:32

标签: javascript loops logic

Fellow Stackers,

我不知道如何使我的“捆绑”功能循​​环。我希望能够传递不同的数量,并根据数量决定哪个盒子/组合是最佳匹配。更大的盒子有更大的折扣。我试图通过减去捆绑了多少项目以及将多少项放入一个框并循环遍历它来实现这一点,但我不确定我的语法有什么问题。任何反馈都将不胜感激。

即1件,将以250美元的价格进入1盒 IE浏览器。 22项,将进入两个10 Box,和两个1 Box。 IE浏览器。 39项,将进入三个10盒,一个5盒,四个1盒

function product(sku, name, quantity, cost) {
      this.sku = sku;
      this.name = name;
      this.quantity = quantity;
      this.cost = cost;
    }

    function bundler(quantity) {
        var remainder = quantity;
        while (remainder > 0) {
        var bundle = [];
        switch (true) {
        case (quantity >= 10):
          box_10 = new product(3333,"Box of 10",1,1500);
          bundle.push(box_10);
          remainder = quantity - 10;
          return bundle;
        case (remainder >= 5 && remainder <= 9):
          box_5 = new product(2222,"Box of 5",1,1000);
          bundle.push(box_5);
          remainder = remainder - 5;
          return bundle;
        case (remainder <=4 && remainder > 0):
          bundle = new product(1111,"Box of 1",remainder,250);
          remainder = remainder - remainder;
          return bundle;
        }
      }
    }

    var order = bundler(19);

1 个答案:

答案 0 :(得分:1)

试试这个;

function product(sku, name, quantity, cost) {
    this.sku = sku;
    this.name = name;
    this.quantity = quantity;
    this.cost = cost;
}

function bundler(quantity) {
    var remainder = quantity;
    var bundle = [];
    while (remainder > 0) {
        if (remainder >= 10){
            var  box_10 = new product(3333,"Box of 10",1,1500);
            bundle.push(box_10);
            remainder = remainder - 10;
        }
        if (remainder >= 5 && remainder <= 9)
        {
            var  box_5 = new product(2222,"Box of 5",1,1000);
            bundle.push(box_5);
            remainder = remainder - 5;
        }
        if (remainder <=4 && remainder > 0){
            var box_1 = new product(1111,"Box of 1",remainder,250);
            bundle.push(box_1);
            remainder = remainder - 1;
        }
    }
    return bundle;
}

alert(bundler(22).length);

Fiddle