在模板字符串中有循环的方法吗?显然可以通过像这样映射一个数组来实现:
array = ["a", "b", "c"]
console.log(`foo ${array.map(i => i).join(" ")} bar`)
///foo a b c bar
但是如果我们需要循环特定次数怎么办?就像这样:
`foo ${for (let i = 0; i <= 10; i++) {Somthing}} bar`
在模板字符串中有循环的方法吗?显然可以通过像这样映射一个数组来实现:
array = ["a", "b", "c"]
console.log(`foo ${array.map(i => i).join(" ")} bar`)
///foo a b c bar
但是如果我们需要循环特定次数怎么办?就像这样:
`foo ${for (let i = 0; i <= 10; i++) {Somthing}} bar`
你可以在那里使用IIFE:
`foo ${(function fun() {
// Do your loop here
// Return the result as a string
})()} bar`
我建议不要这样做,而是创建普通函数,调用它,将返回值分配给一个变量,并在模板字面量占位符中使用该变量。
foo ${(function fun() { string ="" for(let i = 0; i <10 ; i++){ d+= i } return string })()} bar
//"foo 0123456789 bar"然而,这似乎有点奇怪,我应该遵循你的建议。 - Behnam您可以使用 ES6 中的 reducer 实现该功能。
const anArray = [
{
"name": "pulha",
"as": "puli"
},
{
"name": "puli",
"as": "moka"
},
{
"name": "moka",
"as": "starbucks"
},
{
"name": "starbucks",
"as": "sweet"
},
{
"name": "sweet",
"as": "krispey"
},
{
"name": "krispey",
"as": "free"
}
];
$('#an-example-showing-template').append(`
${anArray.reduce((updated, latest) => updated.concat(`<li>${latest.name} alias ${latest.as}</li>`), '')}
`)
#an-example-showing-template > li {
list-style-type: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="an-example-showing-template"></ul>
function helloworld() {
let string;
for(let i = 0; i <10 ; i++){
string = 'Hello World!'
}
return string
}
//Inside the backtick
`${helloworld()}`
const tplFor=(statement,body)=>[...(function*(){}).constructor(`for(${statement})yield\`${body}\``)()].join("");
然后在您的模板中执行 ${tplFor("const person of people","你好!${person.firstName}")}
<table class="table">
<thead style="color: darkred; font-weight: bolder; font-size:22px">
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody style="font-weight: bolder; font-size:16px">
${
(function myfunction() {
let test: string[] = []
for (let item of YourList) {
test.push(
`<tr>
<td>${item.name}</td>
<td>${item.age}</td>
</tr>`
)
}
return test
})()
}
</tbody>
</table>
Something
?你可以将任何循环转换为类似于数组或生成器的东西。 - Nina Scholz