jquery - Check if array is not empty with length JavaScript - Stack Overflow

I console.log(arr) it shows [] but I console.log(arr.length) it shows 0? It's confusing for me, so

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?

Share Improve this question edited Jul 13, 2015 at 5:57 Mike Laren 8,19817 gold badges52 silver badges71 bronze badges asked Jul 11, 2015 at 4:05 Lee shienlongLee shienlong 671 gold badge2 silver badges6 bronze badges 5
  • 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 its length 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
Add a ment  | 

2 Answers 2

Reset to default 4

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'); }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744259429a4565557.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信