如何使用if条件检查数组是否为空?

时间:2019-01-04 17:18:49

标签: javascript arrays if-statement

this.rxInfos的响应返回为空[],但如果条件从未执行过,则下面什么都不知道?

main.js

if (!Array.isArray(this.rxInfos) && this.rxInfos.length === 0) {
            return this.errorHandler(request, 'no rx found in the cache');
        }

2 个答案:

答案 0 :(得分:2)

您可能无法检查数组,或者是否没有长度。

第一部分

!Array.isArray(this.rxInfos)
如果true的值不是数组,则

this.rxInfos

logical OR ||允许结束检查,这很重要,如果第一个操作数为truthy,则很重要。如果没有,则给出一个数组,然后给出第二部分

!this.rxInfos.length

使用长度和它们的logical NOT !进行求值,这意味着,如果长度为零,则最后一部分为true,或者如果长度的值不为零,则该部分的结果为false。 / p>

if (!Array.isArray(this.rxInfos) || !this.rxInfos.length) {
    return this.errorHandler(request, 'no rx found in the cache');
}

答案 1 :(得分:0)

只需先移除!

 if (this.rxInfos !== undefined && Array.isArray(this.rxInfos) && this.rxInfos.length === 0) { return this.errorHandler(request, 'no rx found in the cache'); }