从数组中移除匹配元素

JavaScriptJavaScriptBeginner
立即练习

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

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

简介

在本实验中,我们将探索如何使用 JavaScript 从数组中移除匹配的元素。我们将使用 Array.prototype.filter() 方法来查找与给定条件匹配的元素,并使用 Array.prototype.reduce() 方法从原始数组中移除这些元素。在本实验结束时,你将对如何在 JavaScript 中操作数组有更深入的理解。


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-28587{{"从数组中移除匹配元素"}} javascript/data_types -.-> lab-28587{{"从数组中移除匹配元素"}} javascript/arith_ops -.-> lab-28587{{"从数组中移除匹配元素"}} javascript/comp_ops -.-> lab-28587{{"从数组中移除匹配元素"}} javascript/higher_funcs -.-> lab-28587{{"从数组中移除匹配元素"}} end

从数组中移除匹配的元素

要根据给定条件从数组中移除特定元素,你可以使用 remove 函数。该函数会通过移除给定函数返回 false 的元素来改变原始数组。

以下是使用 remove 函数的步骤:

  1. 打开终端/SSH 并输入 node 开始练习编码。
  2. 使用 Array.prototype.filter() 查找返回真值的数组元素。
  3. 使用 Array.prototype.reduce() 通过 Array.prototype.splice() 移除元素。
  4. 回调函数会被传入三个参数(值、索引、数组)。
const remove = (arr, func) =>
  Array.isArray(arr)
    ? arr.filter(func).reduce((acc, val) => {
        arr.splice(arr.indexOf(val), 1);
        return acc.concat(val);
      }, [])
    : [];

以下是使用 remove 函数的示例:

remove([1, 2, 3, 4], (n) => n % 2 === 0); // [2, 4]

这将返回一个包含已移除元素的新数组。

总结

恭喜你!你已经完成了“从数组中移除匹配元素”实验。你可以在 LabEx 中练习更多实验来提升你的技能。