查找最后 N 个匹配项

JavaScriptJavaScriptBeginner
立即练习

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

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

简介

在这个实验中,我们将探索在数组中找到满足给定条件的最后 n 个元素的概念。我们将学习如何使用 for 循环遍历数组,并对每个元素执行提供的函数。我们还将学习如何使用 Array.prototype.unshift() 方法将匹配的元素添加到结果数组的开头,并在达到所需长度后返回该数组。


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-28307{{"`查找最后 N 个匹配项`"}} javascript/data_types -.-> lab-28307{{"`查找最后 N 个匹配项`"}} javascript/arith_ops -.-> lab-28307{{"`查找最后 N 个匹配项`"}} javascript/comp_ops -.-> lab-28307{{"`查找最后 N 个匹配项`"}} javascript/cond_stmts -.-> lab-28307{{"`查找最后 N 个匹配项`"}} javascript/loops -.-> lab-28307{{"`查找最后 N 个匹配项`"}} javascript/array_methods -.-> lab-28307{{"`查找最后 N 个匹配项`"}} javascript/obj_manip -.-> lab-28307{{"`查找最后 N 个匹配项`"}} end

查找最后 N 个匹配项的说明

要查找满足特定条件的最后 n 个元素,请执行以下步骤:

  1. 打开终端/SSH 并输入 node 开始练习编码。
  2. 使用下面提供的 findLastN 函数。
  3. 提供一个数组 arr 和一个 matcher 函数,该函数为你要匹配的元素返回真值。
  4. 你还可以选择提供要返回的匹配项数量 n(默认值为 1)。
  5. 该函数将使用 for 循环从最后一个元素开始,对 arr 的每个元素执行 matcher 函数。
  6. 如果某个元素符合 matcher 条件,它将使用 Array.prototype.unshift() 添加到结果数组中,该方法会将元素添加到数组开头。
  7. 当结果数组的长度等于 n 时,函数将返回结果。
  8. 如果没有匹配项,或者 n 大于匹配项的数量,则返回空数组。
const findLastN = (arr, matcher, n = 1) => {
  let res = [];
  for (let i = arr.length - 1; i >= 0; i--) {
    const el = arr[i];
    const match = matcher(el, i, arr);
    if (match) res.unshift(el);
    if (res.length === n) return res;
  }
  return res;
};

以下是一些使用 findLastN 函数的示例:

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

总结

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

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