碎片時(shí)間學(xué)編程「338]:檢查數(shù)組是否只有一個(gè)匹配項(xiàng)

檢查數(shù)組是否只有一個(gè)值與給定函數(shù)匹配。 結(jié)合使用 Array.prototype.filter() 方法和 fn 函數(shù)來(lái)查找所有匹配的數(shù)組元素。 使用 Array.prototype.length 方法檢查是否只有一個(gè)元素與 fn 函數(shù)匹配。
JavaScript
const hasOne = (arr, fn) => arr.filter(fn).length === 1;
示例:
hasOne([1, 2], x => x % 2); // truehasOne([1, 3], x => x % 2); // false
更多內(nèi)容請(qǐng)?jiān)L問我的網(wǎng)站:https://www.icoderoad.com
標(biāo)簽: