javascript - 动态更新 JavaScript 数组

标签 javascript arrays

我有一个这样的 JS 数组。

const PaymentMethods = [
    {
      type: "DEBIT",
      cardType: "VISA",
    },
    {
      type: "CREDIT",
      cardType: "VISA",
    }
  ];

如您所见,我现在正在对这些进行硬编码。但是我想动态更新这个 PaymentMethods

例如将有 2 个复选框。 isCreditisDebit

  1. 如果 isCredit = trueisDebit = false,我希望 PaymentMethods 看起来像这样
const PaymentMethods = [
    {
      type: "CREDIT",
      cardType: "VISA",
    }
  ];
  1. 如果 isCredit = falseisDebit = true,我们的 PaymentMethods 应该是
const PaymentMethods = [
    {
      type: "DEBIT",
      cardType: "VISA",
    },
  ];
  1. 如果 isCredit = falseisDebit = false,我们的 PaymentMethods 应该是
const PaymentMethods = [];
  1. 如果 isCredit = trueisDebit = true,我们的 PaymentMethods 应该与顶部的原始方法一样。

有人可以强调我如何做到这一点。我已经搜索了很多,但在这方面还没有找到任何东西。

最佳答案

您有几个选择:

你可以有一个包含这两个条目的主数组,并使用 filterisCredit 的特定值创建过滤版本和 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/

相关文章:

javascript - mustache :仅检查当前上下文中的变量

c++ - 为什么堆栈中没有可变大小的数组?

javascript - 将数组转换为对象+设置属性名称

javascript - 获取文本框的输入类型

javascript - jQuery UI 可靠吗?

javascript - 在 Highcharts 中,如何避免高度有限的容器中的自动刻度间隔

arrays - Runscript 错误 '9' 下标超出范围

javascript - 为什么 array[length] 返回列表的第一个元素?

arrays - 如何在ruby中迭代数组中的特定项目

javascript - Eslint 的正确 YAML - 值不应超过 1 个项目 - 无多个空行