javascript - 如何有条件地呈现逗号和句点?
问题描述
我有三个要有条件地渲染的项目,我希望能够在它们之间渲染逗号,如果是最后一个要渲染的东西,我希望能够渲染一个句点。
{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.');
}
我希望这对你有用。
推荐阅读
- c - 合并带头节点且不带新节点的排序链表(void 函数)
- c# - 如何在 C# 中从一个项目更改依赖项目的代码
- python - 在python中应用规范化函数时出错
- apache-spark - 将 Spark 数据帧写入 delta Lake
- javascript - 尝试从页面 cookie 设置属性到 chrome 扩展 HTML 我有未定义的状态
- vb.net - 如何获取 Oracle.DataAccess.Client?
- java - 如何在 RestAssured 中发送动态 SOAP XML 请求负载
- excel - VBA-无法通过 REST API 更新 SharePoint 2013 项目
- reactjs - 使用 React hooks 进行文件上传组件
- reactjs - 是否可以在每个屏幕安装(导航)中获取数据 React-Native