简介
在本实验中,我们将探索如何根据给定的比较函数从数组中过滤出值。我们将使用 Array.prototype.filter() 和 Array.prototype.findIndex() 方法来实现这一点。此外,如果没有提供比较函数,我们将学习如何使用默认的严格相等比较器。
在本实验中,我们将探索如何根据给定的比较函数从数组中过滤出值。我们将使用 Array.prototype.filter() 和 Array.prototype.findIndex() 方法来实现这一点。此外,如果没有提供比较函数,我们将学习如何使用默认的严格相等比较器。
要根据给定的比较函数从数组中过滤出所有值,请执行以下步骤:
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 中练习更多实验来提升你的技能。