UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

31 lines (29 loc) 1.02 kB
/** * 多参数空值合并函数 * @param {...any} args - 任意数量的参数 * @returns {any} 第一个非null/undefined的参数值 * @example * ```ts * coalesce(null, undefined, 'hello'); // 'hello' * coalesce(undefined, 0, 'x'); // 0 // 0 不是 null/undefined * coalesce(undefined, '', 'x'); // '' // 空串也保留 * coalesce(null, null, null); // null // 全部都是 null/undefined 时返回最后一个参数 * coalesce(); // undefined * ``` */ function coalesce() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } // 遍历所有参数 // eslint-disable-next-line @typescript-eslint/prefer-for-of for (var i = 0; i < args.length; i++) { // 返回第一个非null且非undefined的值 if (args[i] !== null && args[i] !== undefined) { return args[i]; } } // 如果所有参数都是 null/undefined,返回最后一个参数 return args[args.length - 1]; } export { coalesce };