简介
在本实验中,我们将探索如何根据给定的比较函数从数组中过滤出值。我们将使用 Array.prototype.filter() 和 Array.prototype.findIndex() 方法来实现这一点。此外,如果没有提供比较函数,我们将学习如何使用默认的严格相等比较器。
如何根据函数从数组中过滤值
要根据给定的比较函数从数组中过滤出所有值,请执行以下步骤:
- 打开终端/SSH 并输入
node开始练习编码。 - 使用
Array.prototype.filter()和Array.prototype.findIndex()找到合适的值。 - 省略最后一个参数
comp,以使用默认的严格相等比较器。 - 使用以下代码:
const differenceWith = (arr, val, comp = (a, b) => a === b) =>
arr.filter((a) => val.findIndex((b) => comp(a, b)) === -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 中练习更多实验来提升你的技能。