如何将连续序列0,20,40…转换为1,2,3…序列?
Hey there! Let's get this sequence generator working correctly for you.
First, let's clarify your core requirement: you need to map input values like 0 → 1, 20 → 2, 40 → 3, 60 → 4, and so on. The key mathematical pattern here is (input value / 20) + 1 — this formula works for every case in your sequence, including the 0 input!
Your original code had two small issues holding it back:
- The
elsebranch uses division by 10, which would turn 40 into 4 instead of the desired 3 - You don't need separate logic for the 0 case, since the unified formula handles it perfectly
Here's the corrected, simplified function:
function generateSequence(consecutiveSequence) { const output = (consecutiveSequence / 20) + 1; console.log(output); // If you need to guarantee an integer result (in case of unexpected non-multiples of 20), you can use: // console.log(Math.floor(output)); }
Let's test it against your target inputs to confirm:
- Input
0→(0 / 20) + 1 = 1✔️ - Input
20→(20 / 20) + 1 = 2✔️ - Input
40→(40 / 20) + 1 = 3✔️ - Input
80→(80 / 20) + 1 = 5✔️
This should generate exactly the sequence you need. If you anticipate inputs that might not be clean multiples of 20, adding Math.floor() (or Math.round() if you want to handle near-values) will ensure you get whole numbers as output.
内容的提问来源于stack exchange,提问作者sarvesh shukla

