在分配变量之前,如何检查未定义
我使用查找方法提取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”不会返回,因此发现给我以下错误:
错误错误:und offield(在Promise):TypeError:无法读取未定义的属性'ID' TypeError:无法读取未定义的属性
我尝试这样做的属性“ ID”:
const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id ? undefined : '';
我缺少什么?
在下面尝试尝试:
Im using a find method to extract an ID (string) but this is returning an undefined as it doesnt exist.
const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id;
Products has the following:
(2) [ProductInventoryList, ProductInventoryList]
0: ProductInventoryList {_id: "12345", _name: "lineaFija", _productInventoryCharacteristics: ProductInventoryCharacteristics}
1: ProductInventoryList {_id: "12345", _name: "primeraLinea", _productInventoryCharacteristics: ProductInventoryCharacteristics}
length: 2
So "segundaLinea" isnt returned so the find gives me the following error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'id' of undefined
TypeError: Cannot read property 'id' of undefined
I tried doing this but doesnt work:
const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id ? undefined : '';
What am I missing?
Trying the awnser below:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
编辑:
对于打字稿,使用版本3.7 添加了对可选链接的支持。如果您无法更新版本,则必须在多行上进行操作:
如果您必须执行几次,则可能应该写一个助手功能。
You can use optional chaining like this:
Edit:
For Typescript, the support for optional chaining was added with the version 3.7. If you can't update your version you have to do it on multiple lines:
If you have to do this several times, you should probably write a helper function.
如果您不想更新,只需使用可选(?)链接
if you don't want to update, simply use optional(?) chaining