找到前 N 个匹配项

JavaScriptJavaScriptBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索 JavaScript 中的 findFirstN() 函数。此函数用于在数组中查找前 n 个元素,对于这些元素,给定函数返回真值。我们将学习如何将 findFirstN() 与其他数组方法结合使用,以操作和从数组中提取特定数据。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") subgraph Lab Skills javascript/variables -.-> lab-28303{{"`找到前 N 个匹配项`"}} javascript/data_types -.-> lab-28303{{"`找到前 N 个匹配项`"}} javascript/arith_ops -.-> lab-28303{{"`找到前 N 个匹配项`"}} javascript/comp_ops -.-> lab-28303{{"`找到前 N 个匹配项`"}} javascript/cond_stmts -.-> lab-28303{{"`找到前 N 个匹配项`"}} javascript/loops -.-> lab-28303{{"`找到前 N 个匹配项`"}} javascript/array_methods -.-> lab-28303{{"`找到前 N 个匹配项`"}} javascript/obj_manip -.-> lab-28303{{"`找到前 N 个匹配项`"}} end

如何找到前 N 个匹配项

要找到满足特定条件的前 n 个元素,请使用 findFirstN 函数。具体方法如下:

  1. 打开终端/SSH。
  2. 输入 node 开始练习编码。
  3. 使用 findFirstN 函数,传入要搜索的数组、一个匹配函数以及要查找的匹配项数量(如果未指定,默认值为 1)。
  4. matcher 函数将对 arr 的每个元素执行,如果返回真值,则该元素将被添加到结果数组中。
  5. 如果 res 数组的长度达到 n,函数将返回结果数组。
  6. 如果未找到匹配项,则返回空数组。

以下是 findFirstN 函数的代码:

const findFirstN = (arr, matcher, n = 1) => {
  let res = [];
  for (let i in arr) {
    const el = arr[i];
    const match = matcher(el, i, arr);
    if (match) res.push(el);
    if (res.length === n) return res;
  }
  return res;
};

以下是一些使用示例:

findFirstN([1, 2, 4, 6], (n) => n % 2 === 0, 2); // [2, 4]
findFirstN([1, 2, 4, 6], (n) => n % 2 === 0, 5); // [2, 4, 6]

总结

恭喜你!你已经完成了“找到前 N 个匹配项”实验。你可以在 LabEx 中练习更多实验来提升你的技能。

您可能感兴趣的其他 JavaScript 教程