if (!value || value.length<1)
if (value.length<1)
这两个条件有什么区别?不会一样吗?
if (!value || value.length<1)
if (value.length<1)
这两个条件有什么区别?不会一样吗?
不,它们完全不同。
!value
这会检查一个项目是否存在并且它不是未定义的,但这![] and also ![3]
总是错误的。基本上它检查存在。
甚至[]
总是正确的。
length
计算该数组内的元素数量,它纯粹应用于数组。
为了[] , value.length<1 this returns true.
如果value
是null
或undefined
,第二个将抛出一个错误,if
指出您无法访问/ 。length
null
undefined
第一个阻止了这种情况,因为它只会在真实情况下value.length
访问value
。否则,第一个条件 ( !value
) 得到满足,因此第二个条件 ( )value.length < 1
甚至不会被评估。
const arr1 = null;
const arr2 = [];
// Satisfies first condition:
if (!arr1 || arr1.length < 1) console.log('No values in arr1.');
// Satisfies second condition:
if (!arr2 || arr2.length < 1) console.log('No values in arr2.');
// Breaks:
if (arr1.length < 1) console.log('No values in arr1.');
无论如何,这不是特定于 TS 的,它就是 vanilla JS 的工作方式。
快速理解的方法是您无法访问length
未定义数组的属性。所以第二个if
条件会抛出一个类似于Cannot access property 'length' of undefined
.
然而,第一个if
条件检查是否定义了数组。所以它不会抛出任何错误。
Typescript 包含使用“安全导航运算符”或可选链接运算符 ?.
进行此检查的本机方式。所以在TS中,你可以简单地做
if (value?.length < 1) { }
相当于JS
if ((value === null || value === void 0 ? void 0 : value.length) < 1) { }