← 中文资源

简体中文版本

every() 对空数组直接放行

every 在空数组上返回 true、some 返回 false:没有元素能反驳或证明规则;输入可能为空时必须显式判断长度,不能继承空集的默认结论。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

true
true
false
false
true
false

实现说明

整个示例围绕函数 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