javascript 模板文字中的For循环?

igsr9ssn  于 2023-04-19  发布在  Java
关注(0)|答案(4)|浏览(193)

这是一种在模板文字中循环的方法吗?显然,这可以通过Map一个数组来完成:

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`
6l7fqoea

6l7fqoea1#

您可以在此处使用IIFE:

`foo ${(function fun() {
  // Do your loop here
  // Return the result as a string
})()} bar`

我会反对它,只是创建一个普通的函数,调用它,将返回值赋给一个变量,并使用模板文字占位符中的变量。

f0ofjuux

f0ofjuux2#

你可以在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>
pvcm50d1

pvcm50d13#

最好在反勾号表达式之外实现函数,如下所示:

function helloworld() {

let string;

for(let i = 0; i <10 ; i++){
string = 'Hello World!'    
} 
   return string
}

//Inside the backtick

`${helloworld()}`
8yoxcaq7

8yoxcaq74#

const tplFor=(statement,body)=>[...(function*(){}).constructor(`for(${statement})yield\`${body}\``)()].join("");

然后在模板中执行${tplFor(“const person of people”,“hello!${person.firstName}”)}

相关问题