[英]How to check for undefined before assigning to variable
我使用 find 方法来提取 ID(字符串),但这会返回一个未定义的,因为它不存在。
const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id;
产品有以下:
(2) [ProductInventoryList, ProductInventoryList]
0: ProductInventoryList {_id: "12345", _name: "lineaFija", _productInventoryCharacteristics: ProductInventoryCharacteristics}
1: ProductInventoryList {_id: "12345", _name: "primeraLinea", _productInventoryCharacteristics: ProductInventoryCharacteristics}
length: 2
所以“segundaLinea”没有返回,所以 find 给了我以下错误:
错误错误:未捕获(承诺):类型错误:无法读取未定义的属性“id”类型错误:无法读取未定义的属性“id”
我尝试这样做但不起作用:
const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id ? undefined : '';
我错过了什么?
尝试下面的遮阳篷:
您可以像这样使用可选链接:
const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea')?.id;
对于 Typescript,版本 3.7添加了对可选链接的支持。 如果您无法更新您的版本,则必须在多行上进行:
const segundaLinea = products.find(product => product.name === 'segundaLinea');
const additionalLinePhoneNumber = segundaLinea ? segundaLinea.id : "";
如果您必须多次执行此操作,您可能应该编写一个辅助函数。
如果您不想更新,只需添加 if 条件
const segundaLinea = products.find(product => product.name === 'segundaLinea');
if ( segundaLinea && segundaLinea.id ) {
const additionalLinePhoneNumber = segundaLinea.id;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.