0

我正在为一个 uni 项目创建一个购物车,但在测试我的阵列时遇到了问题。如果选择的元素超过 5 个,则总价应有 10% 的折扣。当仅为大于 5 的数量选择一个元素时,变量 discount 可以正常工作,但如果数量在两个元素之间拆分,则返回 0(这意味着如果 POTATOS = 6,则折扣有效,但如果 POTATOS = 4 和 BLUEBERRY = 2,则不再有效)。这里的代码:

    function Calc() {
        var numberPotatos = document.getElementById('potatos_id').value;
        var numberBlueberry =  document.getElementById('blueberry_id').value;
        var numberStrawberry = document.getElementById('strawberry_id').value;
        var numberEggplants = document.getElementById('eggplants_id').value;
        var numberKiwis = document.getElementById('kiwis_id').value;
        var numberBananas = document.getElementById('bananas_id').value;

        var output = "";



        var MyArray= new Array (6); 
            MyArray [0] = numberPotatos;
            MyArray [1] = numberBlueberry;
            MyArray [2] = numberStrawberry;
            MyArray [3] = numberEggplants;
                MyArray [4] = numberKiwis;
            MyArray [5] = numberBananas;

         var MySecondArray  = new Array (6);
MySecondArray [0] = 6;
MySecondArray [1] = 7;
MySecondArray [2] = 5;
MySecondArray [3] = 22;
MySecondArray [4] = 12;
MySecondArray [5] = 4;

// MORE CODE 


var sum = 0;
for(var i=0; i< MyArray.length; i++) {
    sum += MyArray [i ]* MySecondArray[i];
    document.getElementById('test').innerHTML = sum;
}

    var discount = 0;  
    for(var i=0; i<MyArray.length;i++ )
     { 
        if(MyArray[i] > 5){  
           discount = (sum - (sum * 0.10));
            discount = parseFloat(discount);
      }
      document.getElementById('test2').innerHTML = discount;
      }



}
4

2 回答 2

2

您需要跟踪总项目,而不是如果一项超过 5:

var totalItems = 0;
var discount = 0;
for(var i = 0; i < MyArray.length; i++)
{
    totalItems += MyArray[i];
}

if(totalItems > 5){
    discount = (sum - (sum * 0.10));
    discount = parseFloat(discount);
}
于 2013-07-17T16:53:01.603 回答
1

问题是您只检查每篇给定文章的 5 篇以上:

if(MyArray[i] > 5){

不是所有文章,你应该总结所有不同文章的所有部分,所以我建议你这样做:

var sum = 0;
for(var i=0; i< MyArray.length; i++) {
    sum += MyArray [i ]* MySecondArray[i];
}
document.getElementById('test').innerHTML = sum;
var discount = 0;
var totalQuantity = 0;
for(var i=0; i<MyArray.length;i++ ){ 
    totalQuantity += MyArray[i];
}
if(totalQuantity > 5){  
    discount = sum*0.9;
}
document.getElementById('test2').innerHTML = discount;
于 2013-07-17T16:54:02.623 回答