Determine the array is not empty

Posted May 27, 20201 min read

Assuming that the interface data res returned by the background contains a field list, we will only loop when list is not an empty array, otherwise it will report an error, but how to judge that it is not an empty array?
let list = res.list
if(list) {
If(list.length> 0) {
//Loop
}}
}
In the above code, I was performing an array loop in the second layer of judgment. Why do I need to add a layer.list> length> 0 judgment?
In JavaScript, null, number 0, and empty string will be converted to false in the if judgment, but if the background directly returns an empty array \ [], it will be converted to true in the judgment, so it needs to be added One level of judgment is list.length> 0, and you should pay attention when writing judgments. These two judgments are nested and cannot be written as list && list.length> 0. If the value of list is null, list.length> 0 after && An error will be reported because the length property of the list cannot be found during compilation.
ps:The code written as the trinocular operator will be more concise