有条件地解构数组
Destructure array in conditional
我有一个 api returns 数组中的单个布尔值。
如何解构条件中的变量?
let condition = [true];
if (...condition) {
// do stuff
}
我知道我可以使用 condition[0]
,但解构式的解决方案似乎更合理,因为如果数组包含多个值,则可以对每个值进行求值 (let condition = [true, true, true]
)。
只需要一个带有变量的数组。
let [condition] = [true];
对于多个值,您将采用更多变量,例如
let [cond1, cond2, cond3] = [true, false, true];
您可以使用 Array.prototype.every
:
> [true, true].every(x => x)
true
> [true, false].every(x => x)
false
所以:
let condition = [true, true, true];
if (condition.every(x => x)) {
// do stuff
}
我有一个 api returns 数组中的单个布尔值。 如何解构条件中的变量?
let condition = [true];
if (...condition) {
// do stuff
}
我知道我可以使用 condition[0]
,但解构式的解决方案似乎更合理,因为如果数组包含多个值,则可以对每个值进行求值 (let condition = [true, true, true]
)。
只需要一个带有变量的数组。
let [condition] = [true];
对于多个值,您将采用更多变量,例如
let [cond1, cond2, cond3] = [true, false, true];
您可以使用 Array.prototype.every
:
> [true, true].every(x => x)
true
> [true, false].every(x => x)
false
所以:
let condition = [true, true, true];
if (condition.every(x => x)) {
// do stuff
}