【问题标题】:JavaScript Loop, subtracting from a total until nothing remainsJavaScript 循环,从总数中减去,直到没有剩余
【发布时间】:2013-08-07 06:46:32
【问题描述】:

堆垛机朋友,

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

即 1 件商品以 250 美元的价格装入 1 个盒子 IE。 22 件商品,将分为两个 10 盒和两个 1 盒。 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);

【问题讨论】:

  • 为什么不直接使用模除法和 Math.floor?将盒子的类型放入一个整数数组中,并循环遍历其元素。如果 Math.floor 值大于零,则使用该大小的那么多框。如果余数(通过模)大于零,请尝试下一个框大小。将结果存储到一个新的整数数组中。
  • @cabbagery,我不知道该怎么做。也许你可以发布一个例子?

标签: javascript loops logic


【解决方案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

【讨论】:

  • 阿布舍克,非常感谢!将您的代码与我的代码进行比较,看起来我走在正确的道路上,只是在错误的地方有一些逻辑!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多