JavaScript求解CodeWars缺失数组长度问题遇TypeError报错求助
Hey, I see you're stuck on that TypeError while solving the CodeWars "Length of missing array" problem—let's break down what's going wrong and fix it together.
The Root Cause of Your Error
The error you're hitting is a classic array boundary issue. Let's look at your loop:
for (let i = 0; i < arr.length; i++) { // ... else if (arr[i].length - arr[i + 1].length !== 1) { // ... } }
When i reaches the last index of your array (i.e., i = arr.length - 1), i + 1 equals arr.length—which is beyond the array's bounds. At that point, arr[i+1] is undefined, so trying to read arr[i+1].length throws the TypeError you're seeing. The console.log you mentioned probably worked for earlier iterations, but the final loop iteration always triggers the error.
Other Issues in Your Code
Besides the boundary problem, there are a couple of other things that could cause unexpected results:
- You're checking for null/empty subarrays inside the loop, which means you might run several iterations before hitting a null and returning 0. It's better to validate all subarrays upfront.
- Sorting in descending order works, but checking for missing lengths is more intuitive with an ascending sort.
Fixed Code
Here's a revised version of your function that addresses all these issues:
function getLengthOfMissingArray(arr) { // Handle empty or null input immediately if (!arr || arr.length === 0) return 0; // Check all subarrays for null or empty values first for (const subArr of arr) { if (!subArr || subArr.length === 0) return 0; } // Sort subarrays by their length in ascending order arr.sort((a, b) => a.length - b.length); // Loop through adjacent pairs (stop before the last element) for (let i = 0; i < arr.length - 1; i++) { // If the next length isn't exactly 1 more than current, we found the missing one if (arr[i + 1].length - arr[i].length !== 1) { return arr[i].length + 1; } } // If all lengths are consecutive (per problem constraints, this might not be needed, but safe to include) return 0; } console.log(getLengthOfMissingArray([ [5, 2, 9], [4, 5, 1, 1], [1], [5, 6, 7, 8, 9] ])); // Returns 2, which is correct
Key Fixes Explained
- Early Boundary Checks: We first handle null/empty input, then validate every subarray upfront to avoid unexpected errors later.
- Corrected Loop Boundary: By using
i < arr.length - 1, we ensurei + 1never goes beyond the last valid index of the array—no more undefined errors! - Ascending Sort: Sorting from smallest to largest makes it easy to spot the missing length: if the next subarray's length isn't exactly one more than the current, the missing length is
current length + 1. - Immediate Return: As soon as we find the missing length, we return it directly instead of storing it in a variable, making the code cleaner.
Give this a try—it should resolve your TypeError and correctly solve the problem!
内容的提问来源于stack exchange,提问作者yiw qi

