碎片时间学编程「338]:检查数组是否只有一个匹配项

检查数组是否只有一个值与给定函数匹配。 结合使用 Array.prototype.filter() 方法和 fn 函数来查找所有匹配的数组元素。 使用 Array.prototype.length 方法检查是否只有一个元素与 fn 函数匹配。
JavaScript
const hasOne = (arr, fn) => arr.filter(fn).length === 1;
示例:
hasOne([1, 2], x => x % 2); // truehasOne([1, 3], x => x % 2); // false
更多内容请访问我的网站:https://www.icoderoad.com