将计数器值推入数组以生成包含历史值的字符串时遇到功能实现问题
Fixing Your Passenger Counter History Feature
Hey Kevin, let's sort out this issue with saving your counter history—you're super close, just a couple of small missteps!
What's Going Wrong in Your Code
Let's break down the key issues in your save button handler:
- Incorrect array push: You wrote
entries = count.push([0]);which is backwards.push()is a method you call on an array, not a number. Also, this line overwrites yourentriesarray with the return value ofpush()(which is the new length of the array), so you lose your history entirely. - Missing DOM update for history: You have the
entry-infoelement but never update it with theentriesarray content, so even if the array worked, you wouldn't see the history on the page.
Fixed Code with Explanations
Here's the corrected version, with comments pointing out the changes:
"use strict"; let count = 0; let totalPassengerCount = 0; let entries = []; const saveCount = document.getElementById("save-count"); const countEl = document.getElementById("count-el"); const resetCount = document.getElementById("reset-count"); const entry = document.getElementById("entry-info"); // Move this up for global access // Increment button logic (this part was already good!) document .getElementById("incremenet-btn") .addEventListener("click", function () { count += 1; countEl.innerHTML = count; }); // Save button logic with fixes document.getElementById("save-btn").addEventListener("click", function () { totalPassengerCount += count; // 1. Correctly push current count to the entries array entries.push(count); // 2. Update the page to show the history as a readable string entry.innerHTML = `Previous entries: ${entries.join(", ")}`; // Reset current count count = 0; countEl.innerHTML = count; // Update total passenger display saveCount.innerHTML = totalPassengerCount; }); // Reset button logic (added history reset!) resetCount.addEventListener("click", function () { totalPassengerCount = 0; count = 0; entries = []; // Clear the history array countEl.innerHTML = count; saveCount.innerHTML = totalPassengerCount; entry.innerHTML = "Previous entries: "; // Clear the history display }); // Now this logs the actual history array, not a number! console.log(entries);
Key Changes Made:
- Moved the
entryelement selection to the top so it's accessible in all event handlers. - Replaced the broken array push logic with
entries.push(count);to properly store each count value. - Added code to update the
entry-infoelement with a formatted string of your history entries. - Updated the reset handler to clear both the
entriesarray and its display, so everything resets cleanly.
Now when you click save, each count value will be added to your history array, and you'll see a readable list of previous entries on your page. Give it a try!
内容的提问来源于stack exchange,提问作者KevinK
相关产品推荐
相关产品推荐

