You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Find the index of the first element in arr that makes func(arr[i]) return true.
  2. 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).
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:53:15