如何同时检查对象和其他字段中的数组是否为空?

How to check If array is empty in Object and the other fields at the same time?

假设我有这样的对象:

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

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

只要对他们每个的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 为:

The length property of a String object contains the length of the string, in UTF-16 code units

数组长度描述为 here 为:

The length property of an object which is an instance of type Array sets or returns the number of elements in that array.