使用.find()时忽略空值

时间:2019-05-20 13:17:28

标签: javascript arrays typescript object ecmascript-6

我正在使用javascript的.find()方法搜索数组中的值。我收到以下错误:Uncaught TypeError: Cannot read property 'toUpperCase' of null发生在此行:if (this.collection.find(x => x.details.numb.toUpperCase() === numb)) {

我相信会发生此错误,因为x.details.numb中有空值。是否可以在此代码行中忽略空值?还是我必须重新制作没有空值的数组?

4 个答案:

答案 0 :(得分:1)

当然!

x.details && x.details.numb && x.details.numb.toUpperCase() === numb

答案 1 :(得分:1)

您可以在调用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

答案 2 :(得分:1)

只需对DataGridprivate void Window_Activated(object sender, EventArgs e) { int zahler = 0; System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Users\mgleich\source\repos\Inspect\Variablenliste.txt"); //Erstellung Streamreader List<YourType> sourceCollection = new List<YourType>(); while (zahler < 2) { string line = sr.ReadLine(); if (line != "" && line != null) { //create a new Row string[] linearray = line.Split(' '); //add the elements from linearray[0-2] into the new Row sourceCollection.Add(new YourType() { maschinenParameter = linearray[0], valueAdresse = linearray[1] }); } else { zahler++; } } tableAllVar.ItemsSource = sourceCollection; } 进行检查:

null

答案 3 :(得分:1)

由于您处于状况中,因此可以使用some而不是find,因为some会在满足条件后停止(从而获得更好的性能):

this.collection
  .some(item => item && item.details && items.details.numb.toUpperCase() === numb)

如狂野的评论者所言,您还可以防止出现未定义的值:

this.collection
  .some(item => item 
    && item.details 
    && items.details.numb
    && ![undefined, null].includes(items.details.numb)
    items.details.numb.toUpperCase() === numb)