简体   繁体   English

选项链接不适用于 array.length === x

[英]Optioning chaining not working for array.length === x

 let products; if (products?.length !== 0) { console.log('true') }

vs对比

 let products; if (products && products.length !== 0) { console.log('true') }

If there is no product array, example 1 will still run the if statement.如果没有产品数组,示例 1 仍将运行 if 语句。 Shouldn't the optional chaining check to see if product exists, then check for the length and finally check length to 0?可选链接不应该检查产品是否存在,然后检查长度,最后检查长度是否为 0?

Example.例子。 2 will not run if product does not exist.如果产品不存在,2 将不会运行。

Optional chaining does not take precedence over comparison.可选链接不优先于比较。 This这个

if (products?.length !== 0) {

is

if ((products?.length) !== 0) {

It evaluates the chain, then compares the result to 0. If there was a value at the end of the chain, that'll be compared.它评估链,然后将结果与 0 进行比较。如果在链的末尾有一个值,则会进行比较。 If the chain failed due to something being nullish, it'll evaluate to undefined , and that will be compared with 0.如果链因无效而失败,它将评估为undefined 并将与 0 进行比较。

if ((undefined) !== 0) {

which will always be true.这将永远是真的。

Since you want the block to run if products exists and isn't empty, use由于您希望在products存在且不为空的情况下运行该块,因此请使用

if (products?.length) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM