Hey. Can I loop through an array inside a pattern string? For example, there is an array:

"carriers": [ 0: "S7", 1: "SU" ] 

Which I want to output, for example, in the string:

 element.append(` <h2>Carriers:</h2> <div class="carriers"> <img src="/img/carriers/S7.png" /> <img src="/img/carriers/SU.png" /> </div> `); 

And, yes, I am interested in the solution specifically in the body of append() (the specifics of the problem).

    1 answer 1

    If you really want, then you can like this:

     const carriers = ["S7", "SU"]; element.append(` <div class="carriers"> ${carriers.map(name => '<img src="/img/carriers/' + name + '.png" />').join('')} </div> `); 

    But it's better never to do that. Instead, take any JS template engine and use it.

    • "But it's better never to do that." - jsx is watching you warily ) - Qwertiy
    • JS template engine? - JamesJGoodwin
    • If the question is to me, then no more than yes. - Qwertiy
    • @Qwertiy, it's not about JSX. But even there, it is more correct to make complex constructions from map / reduce functions. Although, as always, there may be options. - Dmitriy Simushev
    • @JamesJGoodwin thousands of them. For example, Handlebars.js - Dmitriy Simushev