JavaScript冒泡排序:弹窗缺失问题排查求助
Hey there! Let's break down the two main issues you're facing—the "Fail-Alert missing" test failure and lack of support for negative numbers—along with some small tweaks to get your code fully compliant with the assignment requirements.
Why You're Seeing "Fail-Alert missing"
The biggest culprit here is unhandled edge cases with invalid input:
- If you enter something like
,,,or non-numeric text,str.match(/\d+/g)returnsnull. Callingnull.map(Number)immediately throws a TypeError, stopping the function cold before it reaches thealert()line. - Your bubble sort also has an array out-of-bounds risk: when
jhitsstop-1,arr[j+1]accesses anundefinedvalue (beyond the array's length), which might cause unexpected behavior in test cases.
Fully Fixed Code
Here's the revised code with all issues addressed, plus comments explaining each change:
<form> Enter data to sort : <input type="text" name="mydata" id="mydata" > <!-- Updated ID to match assignment's "mydata" --> <br> <input type="button" id="databtn" onclick="bubble_sort()" name="databtn" value="Sort Data" /> <!-- Updated ID to match assignment's "databtn" --> </form> <script> function swap(arr, first, second){ var temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } function bubble_sort() { var str = document.getElementById("mydata").value; // Use the correct ID for the input var arr = []; // Initialize empty array to avoid null-related errors // Capture numbers (including negatives) and convert to number type var numberMatches = str.match(/-?\d+/g); // -? allows matching negative numbers if (numberMatches) { // Only run map if we found valid numbers arr = numberMatches.map(Number); } // Fixed bubble sort loop to avoid out-of-bounds access var len = arr.length; for(var i = 0; i < len; i++){ // Inner loop stops at len - i - 1 to prevent accessing arr[j+1] beyond the array for(var j = 0; j < len - i - 1; j++){ if(arr[j] > arr[j+1]){ swap(arr, j, j+1); } } } // Ensure alert always fires, even with empty/invalid input alert(arr.length > 0 ? arr.join(', ') : "No valid numbers entered"); } </script>
Key Changes Explained
Fixed Alert Missing Issue:
- Initialized
arras an empty array upfront, so even if no numbers are found, we never callmaponnull. - Added a check for
numberMatchesbefore converting to numbers, preventing TypeError crashes. - The final alert handles empty arrays with a friendly message (you can also just use
alert(arr)if you prefer, but this makes test behavior clearer).
- Initialized
Added Negative Number Support:
- Updated the regex from
/\d+/gto/-?\d+/g—the-?matches an optional negative sign, so negative numbers are now captured correctly.
- Updated the regex from
Complied with Assignment Requirements:
- Changed the input's ID to
mydataand the button's ID todatabtn, matching the exact names specified in your assignment.
- Changed the input's ID to
Fixed Bubble Sort Edge Case:
- Adjusted the inner loop condition to
j < len - i - 1—this ensures we never try to compare the last element in the unsorted portion to a non-existentarr[j+1].
- Adjusted the inner loop condition to
Test It Out!
Try these scenarios to confirm everything works:
- Positive numbers:
3,1,4,2→ Alert shows1, 2, 3, 4 - Negative numbers:
-5,3,-1,0→ Alert shows-5, -1, 0, 3 - Invalid input:
,,,abc→ Alert showsNo valid numbers entered - Empty input: Click the button without typing anything → Alert shows
No valid numbers entered
All these cases will trigger an alert, so you shouldn't see the "Fail-Alert missing" error anymore.
内容的提问来源于stack exchange,提问作者ijustdontget it

