gpt4 book ai didi

javascript - 使用 .find() 时忽略空值

转载 作者:行者123 更新时间:2023-11-30 09:14:21 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com