JavaScript实现Intermediate Algorithm Scripting: Drop it函数结果不符合预期问题求助
Fixing the Drop Elements Function for Intermediate Algorithm Scripting
Let's break down where your current code is going wrong first:
Your current implementation collects all elements that pass the func check into newArr, but the task requires you to stop removing elements as soon as you hit the first element that makes func return true—then return the rest of the array (including elements after that which might not pass the check).
The Correct Approach
You need to:
- Find the index of the first element in
arrthat makesfunc(arr[i])returntrue. - If such an index exists, return a slice of the array starting from that index (this keeps all elements from that point onward, regardless of whether they pass the func check).
- If no element ever passes the check, return an empty array.
Corrected Code
Here's how you can adjust your function using a concise built-in method:
function dropElements(arr, func) { // Find the first index where func returns true const firstMatchIndex = arr.findIndex(func); // If no match found, return empty array; else return the slice from first match onward return firstMatchIndex === -1 ? [] : arr.slice(firstMatchIndex); }
If you prefer to stick with a for loop (similar to your original approach) for more explicit control:
function dropElements(arr, func) { let startIndex = -1; for (let i = 0; i < arr.length; i++) { if (func(arr[i])) { startIndex = i; break; // Stop looping immediately once we find the first valid element } } return startIndex === -1 ? [] : arr.slice(startIndex); }
Testing the Fix
Let's run your test cases again to verify:
dropElements([0, 1, 0, 1], function(n) {return n === 1;})returns[1, 0, 1](first match at index 1, slice includes all remaining elements)dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})returns[3, 9, 2](first match at index 2, slice keeps all elements from that point)
This matches exactly the expected outputs for your task!
内容的提问来源于stack exchange,提问作者Avinash Dhumal
相关产品推荐
相关产品推荐

