我正在使用 javascript 的 .find() 方法在我的数组中搜索值。我收到以下错误:Uncaught TypeError: Cannot read property 'toUpperCase' of null
发生在这一行:if (this.collection.find(x => x.details. numb.toUpperCase() === numb)) {
我认为发生此错误是因为 x.details.numb 中有空值。是否可以忽略这行代码中的空值?还是我必须重新制作没有空值的数组?
最佳答案
您可以在调用 toUpperCase
之前检查空值
if (this.collection.find(x => x.details && x.details.numb && x.details.numb.toUpperCase() === numb)) {
正如@VLAZ 在评论中指出的那样,对于 numb === ''
这将失败,在这种情况下您可以使用
(x.details && x.details.numb || '' ).toUpperCase() === numb
关于javascript - 使用 .find() 时忽略空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56221802/