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

时间:2019-05-16 03:54:22

标签: javascript reactjs ternary-operator conditional-rendering

我有三个要有条件地渲染的项目,我希望能够在它们之间渲染逗号,以及如果要渲染的最后一个项目则用句点表示。

{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时,第三项可能需要一段时间,以此类推。要检查的条件很多,我认为必须有一种更简单的方法来做到这一点?

1 个答案:

答案 0 :(得分:4)

您可以在此处获取数组的帮助。

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.');
}

我希望这对您有用。

相关问题