_.negate(predicate)
_. Predicate
2023-09-11 14:15:01 时间
106
_.negate(predicate)
_negate将predicate方法返回的结果取反
参数
predicate (Function): 需要取反结果的函数
返回值
(Function): 返回新的结果被取反的函数
例子
function isEven(n) { return n % 2 == 0; } _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); // => [1, 3, 5]
源代码:
/** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0 * } * * filter([1, 2, 3, 4, 5, 6], negate(isEven)) * // => [1, 3, 5] */ //将predicate方法返回的结果取反 function negate(predicate) { if (typeof predicate != 'function') {//如果predicate不是function,抛出错误 throw new TypeError('Expected a function') } return function(...args) {//返回一个方法,这个方法将predicate的返回值取反 return !predicate.apply(this, args) } } export default negate