如何在将元素推入数组时使用三元运算符

How to use ternary operator while pushing elements into the array

我正在尝试根据条件将对象添加到数组中。

我的期望是在满足条件时添加两个对象,但我只得到添加的最后一个对象(它的元素丢失)。

const country = ‘USA’

citizenArray.push([
          {
            label: ‘Alex’,
            value: ’32’,
          },
          country === ‘USA’
            ? ({
                label: ‘John’,
                value: ’28’,
              },
              {
                label: ‘Miller’,
                value: ’40’,
              })
            : {
                label: ‘Marsh’,
                value: ’31’,
              },
        ]);

我得到的输出:

[{
            label: ‘Alex’,
            value: ’32’,
          },
{
                label: ‘Miller’,
                value: ’40’,
              }]

预期:

[{
            label: ‘Alex’,
            value: ’32’,
          },
{
                label: ‘John’,
                value: ’28’,
              },
{
                label: ‘Miller’,
                value: ’40’,
              }]

谁能帮我指出哪里做错了?

谢谢。

在 Javascript 中,当您放置 comma-separated expressions within parathesis 时,它将执行每个(从左到右)并将 return 最后一个的结果。

在你的情况下 ({ label: 'John', value: '28',}, { label: 'Miller', value: '40',}) 只得到最后一个对象 { label: ‘Miller’, value: ’40’, } 并添加到数组中。

使用数组然后使用 spread syntax 添加它们。

const country = 'USA';
const citizenArray = [];
citizenArray.push([{
    label: 'Alex',
    value: '32',
  },
  ...(country === 'USA' ? [{
    label: 'John',
    value: '28',
  }, {
    label: 'Miller',
    value: '40',
  }] : [{
    label: 'Marsh',
    value: '31',
  }])
]);

console.log(citizenArray);

像这样使用不同的逻辑:

const country = "USA";
let citizenArray = [];
citizenArray.push([{ label: "Alex", value: "32" }, ...(country == "USA" ? [{ label: "John", value: "28" }, { label: "Miller", value: "40" }] : [{ label: "Marsh", value: "31" }])]);
console.log(citizenArray);
.as-console-wrapper { max-height: 100% !important; top: auto; }