如何检查对象数组是否为空?

How to check if array of object is empty?

我想检查对象数组是否为空,我将 API 调用的结果存储在状态 city_name

cities = this.state.city_name;
console.warn(cities); //this return an empty array []
cities === null ? console.log(cities) : ToastAndroid.showWithGravity('No Result 
                                                                      Found',ToastAndroid.LONG)

我一直收到错误 double java.lang.Double.doubleValue() on a null object。 甚至尝试了 cities.length == 0(this.state.city_name).lenght == 0 它 return 同样的错误。

这是来自 API 调用的数据:

city_name = [{"country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_216.png", "country_id": 216, "country_name": "United States", "discovery_enabled": 1, "has_go_out_tab": 0, "has_new_ad_format": 0, "id": 11282, "is_state": 0, "name": "Del Aire, CA", "should_experiment_with": 0, "state_code": "CA", "state_id": 73, "state_name": "California"}, {"country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_216.png", "country_id": 216, "country_name": "United States", "discovery_enabled": 0, "has_go_out_tab": 0, "has_new_ad_format": 0, "id": 4463, "is_state": 0, "name": "Del Norte, CO", "should_experiment_with": 0, "state_code": "CO", "state_id": 74, "state_name": "Colorado"}, {"country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_216.png", "country_id": 216, "country_name": "United States", "discovery_enabled": 0, "has_go_out_tab": 0, "has_new_ad_format": 0, "id": 9431, "is_state": 0, "name": "Del Rio, TX", "should_experiment_with": 0, "state_code": "TX", "state_id": 111, "state_name": "Texas"}]

请帮帮我

检查数组的长度,然后尝试完成您的任务。

if(cities.length)
// do your task here
else
// handle here

我认为问题可能是您使用的 === 是严格的,您会在双元素上遇到错误。 Null 是一个字符串,double 是一个数字。

if(cities != null && cities.length>0){
    //not empty, do something with data
}else
    //array is empty, so add values.

你可以这样做

 cities = this.state.city_name;
 
 arr = cities.length;
 
 if(arr == 0) {
     console.log('no result found')
       }
 
 else {
     console.log(cities)
       }