我有一個陣列
const data = ["red", "green", "blue"];
我想在地圖中顯示它,以便為它添加一個逗號,但也為倒數第二個元素添加文本“And”。
要獲得以下顯示:"red", "green", and "blue"。
我知道允許我添加comma和 的顯示""。
<div>
{
this.props.data.map(function(item, index) {
return <span key={`${index}`}>{ (index ? ', "' : '"') item }"
</span>;
})
}
</div>
但我不知道在最后一個元素之前添加單詞“and”的解決方案,以防萬一。
你有解決這個問題的方法嗎?
uj5u.com熱心網友回復:
試試這個解決方案
<div>
{this.props.data.map(function (item, index) {
if (index === this.props.data.length - 1)
return (
<span key={`${index}`}>
{(index ? ', and "' : '"') item}"
</span>
);
return <span key={`${index}`}>{(index ? ', "' : '"') item}"</span>;
})}
</div>
uj5u.com熱心網友回復:
請嘗試此解決方案,我認為它會幫助您
{this.props.data.map(function (item, index) {
return (
<span key={`${index}`}>
{index!==this.props.data.length-1? (index ? ', "' :
'"') item : (', and "' item)}"
</span>
);
})}
uj5u.com熱心網友回復:
基于@Borni.Mr 的回答。
<div>
{["red", "blue", "green"].map(function (item, index) {
if (index === ["red", "blue", "green"].length - 1)
return <span key={`${index}`}>{` and "${item}"`}</span>;
return <span key={`${index}`}>{(index ? ', "' : '"') item}"</span>;
})}
</div>
uj5u.com熱心網友回復:
嘗試這個:
一種方法是使用 aternary conditional來檢查最后一項:
<div>
{
this.props.data.map(function(item, index) {
return <span key={`${index}`}>
{ (index === this.props.data.length-1) ? ', and "${item}' : ((index ? ', "' : '"') item) }"
</span>;
})
}
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432131.html
標籤:反应
