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?
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?
- arr.length is the best way to check the length of an array – Jaromanda X Commented Jul 11, 2015 at 4:06
-
3
[]
is an empty array, and therefor itslength
is 0 – what is confusing about that? – C3roe Commented Jul 11, 2015 at 4:06 - Iit is pletely correct ... Javascript arrays are is zero based indexed – leo.fcx Commented Jul 11, 2015 at 4:07
- @CBroe how to check if it's not empty or empty then? – Lee shienlong Commented Jul 11, 2015 at 4:08
-
if (arr.length === 0) { /* array is empty */ }
– nnnnnn Commented Jul 11, 2015 at 4:08
2 Answers
Reset to default 4You 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'); }
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744259429a4565557.html
评论列表(0条)