检查集合是否为空

Pau*_*aul 2 javascript jquery

data.results在尝试对其执行操作之前,如何检查以下内容是否为空?

$.getJSON(myurl, function(data) {
  // if data.results is not empty 
  // {
  //    console.log(data.results.size);
  // }

});
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 7

if (data != null && data.results != null && data.results.length > 0) {
    // the array is not empty
}
Run Code Online (Sandbox Code Playgroud)

  • 上面的代码有多余的部分.`if(data)`与`(data!= null)相同``你可以写`if(data && data.results && data.results.length> 0)` (2认同)