我在下面的代码中没有得到预期的结果,只是想知道它是否是使用表达式在箭头函数语法中添加条件的正确方法。
const drugPriceErrors = [99, 85];
Case#1
const messages = [{
settlementCode: "99",
settlementDesc: "test:test"
}]
Case#2
const messages = [{
settlementCode: "77",
settlementDesc: "test"
}
];
Case#3
const messages = [{
settlementCode: "66",
settlementDesc: "test:test"
}]
function validateEntries(messages) {
if (!messages) {
return []
};
let filteredMsg = messages.filter((item) => {
if (!drugPriceErrors.includes(item.settlementCode)) {
item.settlementDesc.includes(":")
} else {
return;
}
});
return filteredMsg;
};
console.log(validateEntries(messages));
预期产量
Case#1 output should be
[{
settlementCode: "99",
settlementDesc: "test:test"
}]
Case#2 output should be
[]
Case#3 output
[{
settlementCode: "66",
settlementDesc: "test:test"
}]
最佳答案
据我了解,您希望过滤符合以下条件的对象SettlementCode
不应存在于drugPriceErrors
数组中,或者SettlementDesc
应包含:
您可以按以下方式更正代码
首先,由于drugPriceErrors
是数字数组,因此使用settlementCode
将+settlementCode
转换为数字
如果条件评估为true,即settlementCode
中存在drugPriceErrors
,则返回true
否则,返回settlementDesc
是否包含:
const drugPriceErrors = [99,85];
const messages = [ {settlementCode:"99", settlementDesc: "test:test" }, {settlementCode:"66", settlementDesc: "test:test" },{settlementCode: "77",settlementDesc: "test"}];
function validateEntries(messages) {
if (!messages) {
return []
};
let filteredMsg = messages.filter((item) => {
if (drugPriceErrors.includes(+item.settlementCode)) return true;
else return item.settlementDesc.includes(":");
});
return filteredMsg;
};
console.log(validateEntries(messages));
此外,您还可以按以下方式简化代码
const drugPriceErrors = [99,85];
const messages = [ {settlementCode:"99", settlementDesc: "test:test" }, {settlementCode:"66", settlementDesc: "test:test" },{settlementCode: "77",settlementDesc: "test"}];
const result = messages.filter(v => drugPriceErrors.includes(+v.settlementCode) || v.settlementDesc.includes(":"));
console.log(result);
关于javascript - 如何在箭头函数表达式中编写if语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56330985/