判断数组是否为空的方法:检查数组长度( length 属性为 0);使用 Array.isArray() 函数并检查长度;利用 every() 或 some() 函数;使用 for...of 循环。

如何在 JavaScript 中判断数组为空?
判断数组是否为空在 JavaScript 中非常简单,可以通过以下方法实现:
1. 检查数组长度
数组的长度属性 length 表示数组中元素的数量。如果 length 为 0,则数组为空。
const arr = [];
if (arr.length === 0) {
console.log("数组为空");
}2. 使用 Array.isArray()
Array.isArray() 函数检查一个给定值是否是数组。如果值不是数组,该函数将返回 false。
const arr = [];
if (Array.isArray(arr) && arr.length === 0) {
console.log("数组为空");
}3. 使用 every() 和 some()
every() 函数检查数组中的每个元素是否满足给定的条件。some() 函数检查数组中是否有任何元素满足给定的条件。
const arr = [];
if (!arr.every((item) => item === undefined)) {
console.log("数组不为空");
}const arr = [];
if (!arr.some((item) => item !== undefined)) {
console.log("数组为空");
}4. 使用 for...of 循环
for...of 循环迭代数组中的每个元素。如果循环没有执行任何迭代,则数组为空。
const arr = [];
for (let item of arr) {
// 此处代码不会执行,因为数组为空
}
console.log("数组为空");










