基于函数的数组差异

JavaScriptJavaScriptBeginner
立即练习

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

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

简介

在本实验中,我们将探索如何根据给定的比较函数从数组中过滤出值。我们将使用 Array.prototype.filter()Array.prototype.findIndex() 方法来实现这一点。此外,如果没有提供比较函数,我们将学习如何使用默认的严格相等比较器。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced 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/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28323{{"`基于函数的数组差异`"}} javascript/data_types -.-> lab-28323{{"`基于函数的数组差异`"}} javascript/arith_ops -.-> lab-28323{{"`基于函数的数组差异`"}} javascript/comp_ops -.-> lab-28323{{"`基于函数的数组差异`"}} javascript/higher_funcs -.-> lab-28323{{"`基于函数的数组差异`"}} end

如何根据函数从数组中过滤值

要根据给定的比较函数从数组中过滤出所有值,请执行以下步骤:

  1. 打开终端/SSH 并输入 node 开始练习编码。
  2. 使用 Array.prototype.filter()Array.prototype.findIndex() 找到合适的值。
  3. 省略最后一个参数 comp,以使用默认的严格相等比较器。
  4. 使用以下代码:
const differenceWith = (arr, val, comp = (a, b) => a === b) =>
  arr.filter((a) => val.findIndex((b) => comp(a, b)) === -1);
  1. 使用以下示例测试你的函数:
differenceWith(
  [1, 1.2, 1.5, 3, 0],
  [1.9, 3, 0],
  (a, b) => Math.round(a) === Math.round(b)
); // 预期输出:[1, 1.2]

differenceWith([1, 1.2, 1.3], [1, 1.3, 1.5]); // 预期输出:[1.2]

总结

恭喜你!你已经完成了“基于函数的数组差异”实验。你可以在 LabEx 中练习更多实验来提升你的技能。

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