如何有条件地呈现逗号和句点?

How to conditionally render commas and periods?

我有三个要有条件地呈现的项目,我希望能够在它们之间呈现逗号,如果它是最后要呈现的东西,我希望能够呈现一个句点。

{this.state.a&&i++}    
{this.state.b&&i++}  
{this.state.c&&i++}                  
{this.state.a && (i==1?"item a.":"item a,")}
{this.state.b && (i==2?"item b.":"item b,")}
{this.state.c && (i==3?"item c.":"item c,")}

所以这显然是行不通的,因为当 i=1 时其他项目可能是唯一的项目,当 i=2 时第三项可能需要一个句点,等等。看起来就像要检查的许多条件一样,我假设必须有更简单的方法来做到这一点?

你可以在这里得到数组的帮助。

const newArray = [];
{this.state.a && newArray.push('item a')};
{this.state.b && newArray.push('item b')};
{this.state.c && newArray.push('item c')};

if (newArray.length) {
  console.log(`${newArray.join(',')}.`);
} else {
  console.log('No items present.');
}

希望这对你有用。