ES6/JS:如果数组.find返回undefined,如何分配默认值

14

如果array.find返回“undefined”,我该如何为变量设置默认值。

以下是导致问题的行。在某些情况下,这个变量会被填充,但在其他情况下,它不会被填充,在这种情况下,我希望它默认为0。

this.statistics.creditAmount = response.data.find(t => t.paymentType == 'RF' && t.status == 1).amount || 0;

3
你可以用这个代码:(response.data.find(t => t.paymentType == 'RF' && t.status == 1) || { amount : 0 }).amount。但是,使用if-else语句或三目运算符会更易读(在我看来)。 - adiga
1
没有必要创建一个无法运行的代码片段。 - user47589
虽然不太易读,但 @adiga 的方法确实很有效。双竖线的作用是什么? - Dally
1
(data.find(t => t.paymentType == 'RF' && t.status == 1) || { amount : 0 })代码块首先检查找到的对象是否有值。如果它是“undefined”,OR运算符将使用第二个对象“{ amount : 0 }”。然后从返回的对象中获取“amount”属性。 - adiga
4个回答

10

我看到这个问题已经被回答了,但我认为我可以做出一些贡献

const { amount = 0 } = response.data.find(t => t.paymentType === 'RF' && t.status === 1) || {};
this.statistics.creditAmount = amount;

或者您可以使用一个reducer:

  this.statistics.creditAmount = response.data.reduce((amt, t) => t.paymentType === 'RF' && t.status === 1 ? t.amount : amt, 0);

当reducer遍历整个数组时,会使用更多的时钟周期,而Array.prototype.find则在找到第一个匹配项后停止。这也可能导致结果有所不同,因为reducer的编写方式是取匹配的最后一项


6
您的代码问题在于,对于array.find返回undefined的情况,您正在访问.amount中的undefined。您可以通过添加保护来解决它:
const credit = response.data.find(t => 
  t.paymentType == 'RF' && t.status == 1);

this.statistics.creditAmount = credit ? credit.amount : 0;


1
另一种方法是使用闭包和解构,配合默认对象/值。
const
    getAmount = ({ amount = 0 } = {}) => amount,
    credit = getAmount(response.data.find(t => t.paymentType == 'RF' && t.status == 1));

0
可能有点过度设计,但是你可以创建并实现一个可重用的空值传播方法。

const response = {data: []};

const _try = (func, fallbackValue) => {
    try {
        var value = func();
        return (value === null || value === undefined) ? fallbackValue : value;
    } catch (e) {
        return fallbackValue;
    }
}


const result = _try(() => response.data.find(t => t.paymentType == 'RF' && t.status == 1).amount, 0);
console.log(result);

这篇文章最初是由Tocqueville作为这个答案的一部分编写的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接