如何将currentIndex始终设为0并修正价格计算重复累加问题
Hey Ben, let's work through your two problems one by one to get things working as expected:
1. Reset currentIndex to 0 on every calculation
To make sure currentIndex always starts at 0 before each calculation, just add a reset line at the very start of your calculation function. Assuming your logic is wrapped in a function like calculatePrice(), modify it like this:
function calculatePrice() { currentIndex = 0; // Add this line to reset the index every time calculation runs // Your existing calculation code here... }
If currentIndex is declared inside the function, either initialize it to 0 when declaring or explicitly reset it at the start to avoid leftover values from previous runs.
2. Fix the price calculation logic (duplicate value issue)
Your expected total is (0 + selected value) but you're getting (selected value + selected value)—this means both parts of your formula (CRANK1 + CRANK2) + (DRANK1 + DRANK2) are evaluating to the selected value, doubling the total.
What's causing this:
Chances are, you're accidentally assigning the selected price value to both the CRANK and DRANK variable groups. For example, both CRANK1/CRANK2 and DRANK1/DRANK2 are pulling the same value from your prices array instead of one group being set to 0.
How to fix it:
Ensure only one group uses the selected value, and the other is explicitly set to 0. For example, if you want the DRANK group to hold the selected value and CRANK to be 0:
// Reset all variables first to clear leftover values from prior calculations CRANK1 = 0; CRANK2 = 0; DRANK1 = prices[yourSelectedIndex]; // Replace with your actual selected index logic DRANK2 = 0; // Calculate the price now const totalPrice = (CRANK1 + CRANK2) + (DRANK1 + DRANK2); // Will equal 0 + selected value
Or if your logic is that only one specific variable holds the selected value (e.g., CRANK2), make sure the rest are 0:
CRANK1 = 0; CRANK2 = prices[yourSelectedIndex]; DRANK1 = 0; DRANK2 = 0; const totalPrice = (CRANK1 + CRANK2) + (DRANK1 + DRANK2); // Still equals 0 + selected value
Always remember to reset these CRANK/DRANK variables at the start of each calculation to prevent old values from carrying over and messing up your sum.
内容的提问来源于stack exchange,提问作者Ben

