length 和 typeof == undefined 被忽略,lodash

length and typeof == undefined being ignored, lodash

希望我的 codepen 足够清晰,第一次使用它 - https://codepen.io/jsfo011/pen/GRojmpw

notEmpty 来自我的数据库 JSON。我写了一个函数来遍历它并找到与参数匹配的行,returning 值。

如果我的函数找不到匹配的行,我想 return 0.

我认为我写的东西会起作用,但我不断收到

"jQuery.Deferred exception: Cannot read property 'total_income' of undefined" "TypeError: Cannot read property 'total_income' of undefined

但是当匹配时它似乎工作正常。

我错过了什么?

如果过滤后的income没有单值(空列表),则single[0]未定义。因此,以下代码试图访问未定义的 属性 "total_income"

income[0]["total_income"]

您需要确保仅当父对象 income[0] 有效时才访问 属性。

一种方法是添加另一个检查以确保 income 在我们像这样访问它之前在列表中至少有一个值:

if (income && income.length) {
  if (income[0]["total_income"] !== undefined) {
    return parseFloat(income[0]["total_income"]);
  }
}

该行检查以确保定义了 income 并且至少有一个值。

输出:

    Empty Data - 0
    Found - 1000
    Not found - 0

希望这有助于理解问题。

为什么不直接使用 lodash.get( ) 和默认值 0:

function calculate(data, income_type) {
        let income = _.filter(data, {'income_type': income_type});
        let incomeValue = _.get(income, '0.total_income', 0);
        return parseFloat(incomeValue);
    }