【问题标题】:How to add more text with forEach inside a string?如何在字符串中使用 forEach 添加更多文本?
【发布时间】:2019-06-24 22:36:23
【问题描述】:

所以,我不知道这在 JS 中是否可行,我想做的是这样的:

我有 N 个对象,并想用它们制定一个 XML

import config from './config'; //that actually doesent matter
//just show it here because the xml that I return have a LOT of data
//from this config

buildXML(objects) => {
 return `
   <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
   <my-xml>
     <id>${config.id}</id>
     ${objects.forEach(object) => {
       return '<object>' + object + '</object>'
     }}
   </my-xml>
 `
}

我想要这样的结果

  <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
   <my-xml>
     <id>42</id>
     <object> OBJECT </object>
     <object> OBJECT </object>
   </my-xml>

有什么办法可以做到吗?欢迎任何帮助:) 谢谢!

【问题讨论】:

    标签: javascript xml string foreach


    【解决方案1】:

    例如:

    return `
       <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
       <my-xml>
         <id>${config.id}</id>
         ${objects.map(object => {
           return '<object>' + object + '</object>'
         }).join('')}
       </my-xml>`;
    

    甚至更短:

    return `
       <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
       <my-xml>
         <id>${config.id}</id>
         ${objects.map(object => `<object>${object}</object>`).join('')}
       </my-xml>`;
    

    【讨论】:

    • 不知道我必须使用 .join('')... 谢谢 idmean!
    猜你喜欢
    • 2011-10-20
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2016-01-17
    • 2012-12-18
    相关资源
    最近更新 更多