[英]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
它返回相同的错误。
这是来自 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
你可以做这样的事情
cities = this.state.city_name; arr = cities.length; if(arr == 0) { console.log('no result found') } else { console.log(cities) }
我认为问题可能在于您使用的是严格的 === 并且您将在双元素上收到错误。 Null 是一个字符串,double 是一个数字。
if(cities != null && cities.length>0){
//not empty, do something with data
}else
//array is empty, so add values.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.