[英]ES6 map array to string without comma
I am trying to map a list of errors into a list that I will show in a tooltip.我正在尝试将错误列表映射到我将在工具提示中显示的列表中。 The list added, but there's a
,
added between every li element.添加了列表,但在每个 li 元素之间添加了
,
。
I guess this is because this basically does errors.map(error => ...).toString()
in the end.我猜这是因为这基本上是在最后执行
errors.map(error => ...).toString()
。 Any ideas how I can map the strings in errors
array without having this comma added?任何想法如何在不添加此逗号的情况下映射
errors
数组中的字符串?
data-tip = {`
Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
<ul>
${errors.map(error => `<li>${error}</li>`)}
</ul>
`}
.toString()
of the array object uses Array.prototype.join
method for converting the array into a string.数组对象的
.toString()
使用Array.prototype.join
方法将数组转换为字符串。 The .join
method by default uses ,
for joining the elements. .join
方法默认使用,
来连接元素。 You can replace the .toString()
with .join('')
.您可以用
.join('')
替换.toString()
.join('')
。
In your code, you are using template literals which returns you a string and hence the code在您的代码中,您使用的是模板文字,它返回一个字符串,因此代码
${errors.map(error => `<li>${error}</li>`)}
is converted to a string using a toString()
function which by default joins the returned array with a ,
.使用
toString()
函数将其转换为字符串,该函数默认将返回的数组与,
。
You can make use of join with anly other separator like您可以将 join 与其他分隔符一起使用,例如
{`
Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
<ul>
${errors.map(error => `<li>${error}</li>`).join(' ')}
</ul>
`}
You can try this way ::你可以试试这个方法::
let arrayOfStr = [10, 20, 45, 12, 65 ];
let myNumberOfStr = arrayOfStr.map( number => `myNumber_${number}` ).join(' ');
console.log(myNumberOfStr);
// "myNumber_10 myNumber_20 myNumber_45 myNumber_12 myNumber_65"
Just use reduce
.只需使用
reduce
。 Like this:像这样:
data-tip = {` Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br> <ul> ${errors.reduce( (prevError, currentError) => `${prevError}<li>${currentError}</li>`, '', )} </ul> `}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.