![](/img/trans.png)
[英]How can I force React to re-render all components on a page that come from array.map?
[英]How can I modify the last iteration of a Array.map?
目前,我有以下 map
Array.map(i => `${i},`)
它返回
element1,element2,element3,
但我需要它返回
element1,element2,element3
避免最后一個逗號。
我怎樣才能以一種功能性的方式做到這一點?
解決此特定問題的更好方法可能是使用join
而不是map
。
但是,要使用 map 解決此問題,請查看傳遞給回調的其他 arguments:
map((element, index, array) => { ... } )
您可以使用index === array.length - 1
確定您是否在最后一個元素上
我怎樣才能以一種功能性的方式做到這一點?
console.log( ['a', 'b', 'c', 'd'].reduce((x, y) => `${x},${y}`) )
您也可以像這樣使用.toString()
或.join()
。
const arr = [ 'element1', 'element2', 'element3' ]; console.log(arr.toString()); console.log(arr.join()); // The same as console.log(arr.join(','));
toString()
方法返回一個包含所有數組值的字符串,以逗號分隔。
join()
方法將數組作為字符串返回。 元素將由指定的分隔符分隔。 默認分隔符是逗號 (,)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.