我正在为一个 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;
}
}