根据函数从数组中提取值

JavaScriptJavaScriptBeginner
立即练习

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

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

简介

在本实验中,我们将探索 JavaScript 中的 pullBy() 函数。该函数允许我们根据给定的迭代函数从数组中过滤出特定的值。在本实验结束时,你将了解如何使用 pullBy() 来操作数组并有效地过滤掉不需要的值。


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/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28562{{"`根据函数从数组中提取值`"}} javascript/data_types -.-> lab-28562{{"`根据函数从数组中提取值`"}} javascript/arith_ops -.-> lab-28562{{"`根据函数从数组中提取值`"}} javascript/comp_ops -.-> lab-28562{{"`根据函数从数组中提取值`"}} javascript/array_methods -.-> lab-28562{{"`根据函数从数组中提取值`"}} javascript/obj_manip -.-> lab-28562{{"`根据函数从数组中提取值`"}} javascript/higher_funcs -.-> lab-28562{{"`根据函数从数组中提取值`"}} javascript/destr_assign -.-> lab-28562{{"`根据函数从数组中提取值`"}} javascript/spread_rest -.-> lab-28562{{"`根据函数从数组中提取值`"}} end

如何根据给定函数从数组中提取值

要开始练习编码,请打开终端/SSH 并输入 node

pullBy 函数会根据给定的迭代函数过滤掉指定的值,从而改变原始数组。其工作原理如下:

  1. 检查提供的最后一个参数是否为函数。
  2. 使用 Array.prototype.map() 将迭代函数 fn 应用于所有数组元素。
  3. 使用 Array.prototype.filter()Array.prototype.includes() 提取不需要的值。
  4. 设置 Array.prototype.length 将传入数组的长度重置为 0
  5. 使用 Array.prototype.push() 仅用提取的值重新填充数组。

以下是代码:

const pullBy = (arr, ...args) => {
  const length = args.length;
  let fn = length > 1 ? args[length - 1] : undefined;
  fn = typeof fn == "function" ? (args.pop(), fn) : undefined;
  let argState = (Array.isArray(args[0]) ? args[0] : args).map((val) =>
    fn(val)
  );
  let pulled = arr.filter((v, i) => !argState.includes(fn(v)));
  arr.length = 0;
  pulled.forEach((v) => arr.push(v));
};

以下是使用它的示例:

var myArray = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }];
pullBy(myArray, [{ x: 1 }, { x: 3 }], (o) => o.x); // myArray = [{ x: 2 }]

请注意,在这个示例中,我们提取了所有 x 属性为 13 的元素。最终的 myArray 将只包含 x 属性为 2 的元素。

总结

恭喜你!你已经完成了“根据函数从数组中提取值”实验。你可以在 LabEx 中练习更多实验来提升你的技能。

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