实现说明
整个示例围绕函数 approvedForCheckout组织。
使用要点
- 守卫
ages.length === 0一旦成立就走提前的return,把后续流程挡掉。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 approvedForCheckout。
主签名形如 default function approvedForCheckout(ages)
核心语句
return ages.every((age) => age >= 18);
代码示例
const gates = {
// every() on empty arrays is vacuously true: no item contradicts the rule
allAdults: (ages) => ages.every((age) => age >= 18),
// some() on empty arrays is always false: no item can prove the rule
hasMinor: (ages) => ages.some((age) => age < 18),
};
console.log(gates.allAdults([19, 21])); // true
console.log(gates.allAdults([])); // true <- empty input slips through
console.log(gates.hasMinor([19, 21])); // false
console.log(gates.hasMinor([])); // false
// Decide the empty case explicitly instead of inheriting the vacuous default
function approvedForCheckout(ages) {
if (ages.length === 0) return false; // no guests is not a valid booking
return ages.every((age) => age >= 18);
}
console.log(approvedForCheckout([19, 21])); // true
console.log(approvedForCheckout([])); // false