如何正确判断一个数组是否为空

判断数组是否为空——错误的方法

const arr = []

if (arr) {
  console.log('true')
} else {
  console.log('false')
}

// true

为什么空数组为 true 呢?
在这里插入图片描述
发现空数组展开里面还是有默认的属性


判断数组是否为空——正确的方法

if (arr && arr.length > 0) {
  console.log('true')
}

判断一个数组是否为空,必须判断它的length > 0

发布了23 篇原创文章 · 获赞 0 · 访问量 554

猜你喜欢

转载自blog.csdn.net/JIANLI0123/article/details/104684724
今日推荐