检查数组是否为空时,我应该使用 array.length <= 0 还是 array.length === 0?

When checking if an array is empty, should I use array.length <= 0 or array.length === 0?

我习惯用array.length <= 0检查空数组。当然数组的长度永远不能小于0。这是我养成的习惯,以确保我的程序运行"just in case something weird happens"。有什么理由不使用 <= 运算符而改用 === 0 吗?

在我看来,没有理由检查长度的负值 list.length <= 0. as specs for Arrays says:

Every Array object has a length property whose value is always a nonnegative integer less than 232.

所以完全有资格检查list.length === 0

如果 list 是一个数组,那么不,length 不可能是整数以外的任何值。来自 specification:

Every Array object has a non-configurable "length" property whose value is always a nonnegative integer less than 2 ** 32

给定一个数组对象,您甚至不能通过将 length 更改为有效长度之外的其他内容来故意使事情变得混乱;将抛出错误:

const arr = [];
Object.defineProperty(arr, 'length', { value: -5 })