如何在数组项之间添加逗号? [英] How to add comma between array items?
本文介绍了如何在数组项之间添加逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当使用map函数打印出所有值时,如何在值之间添加逗号? (使用React,这就是为什么我有钥匙等。)
How can I add a comma between the values, when using map function to print out all the values? (Using React, that's why I have the key etc.)
{ cars.map(car => {
return(
<p key={car.id}>{car.title} ,</p>
);
}); }
这就是我想要的结果,最后没有逗号最后一个数组项目:
This is how I would like the result to be, with no comma in the end of the last array item:
Audi, Nissan, Mazda, Toyota
我应该这样做吗?
{ cars.map((car, index) => {
const separator = ", ";
if(index === car.length - 1) {
return(
<p key={car.id}>{car.title} + separator </p>
);
}
});
}
推荐答案
你可以知道哪个电话 map
的回调是最后一个使用你传递的索引参数:
You can know which call to map
's callback is the last by using the index argument you get passed:
{ cars.map((car, index) => {
return(
<p key={car.id}>{car.title} {index < cars.length - 1 ',\u00A0' : ''}</p>
);
}); }
附注:不需要冗长的箭头函数体(当然它可以作为样式选择):
Side note: No need for the verbose arrow function body (though of course it's fine as a style choice):
{ cars.map((car, index) =>
<p key={car.id}>{car.title} {index < cars.length - 1 ? ',\u00A0' : ''}</p>)
}
实例:
const cars = [
{id: 1, title: "Ford"},
{id: 2, title: "Toyota"},
{id: 3, title: "Lexus"}
];
ReactDOM.render(
<div>
{ cars.map((car, index) =>
<p key={car.id}>{car.title}{index < cars.length - 1 ? ',\u00A0' : ''}</p>)
}
</div>,
document.getElementById("root")
);
/* To make the result match the question */
p { display: inline-block; }
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
这篇关于如何在数组项之间添加逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文