为什么布尔值的解构在 javascript 中有效?

Why does destructuring on boolean is working in javascript?

为什么解构布尔值有效。例如

const condition = true
const toto = { name: 'toto' }

const other = {
   other: 'other',
   ...condition && toto
}
console.log({ other }) // { other: 'other', name: 'toto' }

const falseCondition = false

const otherWithoutToto = {
   other: 'other',
   ...falseCondition && toto
}

console.log({ otherWithoutToto }) // { other: 'other' }

如果是false boolean,我们不加属性,否则加。实际上它运行良好,但有人可以向我解释为什么这可能吗?

您在这里使用的不是 destructuring, it's object property spread. It requires that the expression to the right-hand side (RHS) of the ... evaluates to either an object or something that can be converted to one (with exceptions for null and undefined). It then takes the -enumerable properties from the object and copies them 正在创建的对象。对于您的示例,以下代码可能会出现两种可能性:

...(condition && toto)
  1. conditiontrue,因此上面的表达式求值为对象 toto。它的计算结果不是布尔值,而是最后一个真实值,在您的情况下是对象 toto。对象 属性 传播语法然后从对象中获取自己可枚举的属性并将它们添加到正在创建的对象中。

  2. conditionfalse,因此上述表达式的计算结果为 false。这意味着 JavaScript 将上述代码视为 ...false。由于 false 是原始类型而不是对象,JavaScript 尝试通过 wrapping it in a boolean object:

    将其转换为一个对象
    ...new Boolean(false)
    

    既然 ... 的 RHS 已经转换为一个对象,JavaScript 然后获取布尔对象的自己可枚举的属性并将它们添加到正在创建的对象中。由于布尔值没有任何可枚举的自有属性,因此不会向创建的对象添加任何内容。