如果array.find返回'undefined‘,如何为变量设置默认值。
下面这行代码引起了我的问题。在某些情况下,此变量将填充,但在其他情况下,它不会填充,在这种情况下,我希望它缺省为0。
this.statistics.creditAmount = response.data.find(t => t.paymentType == 'RF' && t.status == 1).amount || 0;
发布于 2019-03-27 03:45:59
代码的问题在于,在array.find
返回undefined
的情况下访问undefined
的.amount
。你可以通过添加一个防护来解决这个问题:
const credit = response.data.find(t =>
t.paymentType == 'RF' && t.status == 1);
this.statistics.creditAmount = credit ? credit.amount : 0;
发布于 2019-03-27 03:51:12
另一种方法是使用闭包和具有默认对象/值的解构。
const
getAmount = ({ amount = 0 } = {}) => amount,
credit = getAmount(response.data.find(t => t.paymentType == 'RF' && t.status == 1));
发布于 2019-03-27 03:55:18
可能的过度杀伤力,但您可以创建并实现一个可重用的空传播方法。
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作为this answer的一部分编写的。
https://stackoverflow.com/questions/55365114
复制相似问题