For Loop inside Template Literals?
For Loop inside Template Literals?
这是一种在模板文字中循环的方法吗?显然这可以通过映射这样的数组来完成:
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`
我建议不要这样做,只需创建普通函数,调用它,将 return 值分配给一个变量,然后在模板文字占位符中使用该变量。
在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()}`
这是一种在模板文字中循环的方法吗?显然这可以通过映射这样的数组来完成:
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`
我建议不要这样做,只需创建普通函数,调用它,将 return 值分配给一个变量,然后在模板文字占位符中使用该变量。
在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()}`