我有一个这样的 JS 数组。
const PaymentMethods = [
{
type: "DEBIT",
cardType: "VISA",
},
{
type: "CREDIT",
cardType: "VISA",
}
];
如您所见,我现在正在对这些进行硬编码。但是我想动态更新这个 PaymentMethods
例如将有 2 个复选框。 isCredit
和 isDebit
- 如果
isCredit = true
和isDebit = false
,我希望PaymentMethods
看起来像这样
const PaymentMethods = [
{
type: "CREDIT",
cardType: "VISA",
}
];
- 如果
isCredit = false
和isDebit = true
,我们的PaymentMethods
应该是
const PaymentMethods = [
{
type: "DEBIT",
cardType: "VISA",
},
];
- 如果
isCredit = false
和isDebit = false
,我们的PaymentMethods
应该是
const PaymentMethods = [];
- 如果
isCredit = true
和isDebit = true
,我们的PaymentMethods
应该与顶部的原始方法一样。
有人可以强调我如何做到这一点。我已经搜索了很多,但在这方面还没有找到任何东西。
最佳答案
您有几个选择:
你可以有一个包含这两个条目的主数组,并使用 filter
为 isCredit
的特定值创建过滤版本和 isDebit
标志:
let paymentMethods = AllPaymentMethods.filter(({type}) => type === "CREDIT" && isCredit || type === "DEBIT" && isDebit);
实例:
const AllPaymentMethods = [
{
type: "DEBIT",
cardType: "VISA",
},
{
type: "CREDIT",
cardType: "VISA",
}
];
const isCredit = Math.random() < 0.5;
const isDebit = Math.random() < 0.5;
let paymentMethods = AllPaymentMethods.filter(({type}) => type === "CREDIT" && isCredit || type === "DEBIT" && isDebit);
console.log(`isCredit: ${isCredit}, isDebit: ${isDebit}, paymentMethods = ${JSON.stringify(paymentMethods)}`);
Run repeatedly to see different values of <code>isCredit</code> and <code>isDebit</code>.
或者您可以拥有单独的条目并使用一对 if
构建数组声明:
const isDebit = Math.random() < 0.5;
const isCredit = Math.random() < 0.5;
let paymentMethods = [];
if (isCredit) {
paymentMethods.push(creditOption);
}
if (isDebit) {
paymentMethods.push(debitOption);
}
实例:
const debitOption =
{
type: "DEBIT",
cardType: "VISA",
};
const creditOption =
{
type: "CREDIT",
cardType: "VISA",
};
const isDebit = Math.random() < 0.5;
const isCredit = Math.random() < 0.5;
let paymentMethods = [];
if (isCredit) {
paymentMethods.push(creditOption);
}
if (isDebit) {
paymentMethods.push(debitOption);
}
console.log(`isCredit: ${isCredit}, isDebit: ${isDebit}, paymentMethods = ${JSON.stringify(paymentMethods)}`);
Run repeatedly to see different values of <code>isCredit</code> and <code>isDebit</code>.
关于javascript - 动态更新 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58753882/