【问题标题】:How to check If array is empty in Object and the other fields at the same time?如何同时检查 Object 和其他字段中的数组是否为空?
【发布时间】:2021-08-26 13:13:51
【问题描述】:

假设我有一个看起来像这样的对象:

filter: {
masterName: '',
service:[],
}

如何检查数组和 masterName 字段是否为空?

【问题讨论】:

  • 检查数组长度和字符串长度。
  • 过滤对象除了数组和字符串还有哪些类型的值

标签: javascript arrays object iteration


【解决方案1】:

只需评估它们每个的length属性,看看长度是否为0,如下例所示:

var filter = {
  masterName: '',
  service: [],
}

// Checks whether masterName is zero-length
if (filter.masterName.length === 0) {
  console.log('masterName is empty');
}

// Checks whether service is zero-length
if (filter.service.length === 0) {
  console.log('service is empty');
}

// Checks whether either are zero-length
if (filter.masterName.length === 0 && filter.service.length === 0) {
  console.log('Both are empty');
}

字符串长度被描述为here

String 对象的长度属性包含字符串的长度 字符串,UTF-16 编码单元

数组长度被描述为here

对象的长度属性,它是 Array 类型的实例 设置或返回该数组中元素的数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2018-12-02
    • 2018-09-29
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多