I console.log(arr)
it shows []
but I console.log(arr.length)
it shows 0
? It's confusing for me, so what is the best way to check if an array contain something?
You can check if an array is empty by checking the length
property:
if (arr.length === 0) {
// arr is empty
}
Or, to check if it contains some items:
if (arr.length) {
// arr is not empty
}
console.log(arr)
will show []
for an empty array. That's just how it shows that and a length
property of 0
means that there are no items in the array.
This is an array: ['1','2','3','4'], so if the array is empty it will look like this: []. I would do like this:
if(arr && arr.length){ console.log('then the array is created and it has value'); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.