模板字面量中使用的 For 循环?

17

在模板字符串中有循环的方法吗?显然可以通过像这样映射一个数组来实现:

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`

2
模板字面量允许嵌入表达式,而不是语句。考虑分享您正在尝试解决的问题,因为目前似乎这是一个 XY 问题 - Tyler Roper
什么是Something?你可以将任何循环转换为类似于数组或生成器的东西。 - Nina Scholz
5个回答

13

你可以在那里使用IIFE:

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

我建议不要这样做,而是创建普通函数,调用它,将返回值分配给一个变量,并在模板字面量占位符中使用该变量。


1
谢谢,这样做可以完成工作: foo ${(function fun() { string ="" for(let i = 0; i <10 ; i++){ d+= i } return string })()} bar //"foo 0123456789 bar"然而,这似乎有点奇怪,我应该遵循你的建议。 - Behnam
1
你能详细说明一下为什么你建议不这样做吗? - robfuscator
@robfuscator 或许是为了可读性考虑。我自己也没有看到其他的东西。 - Syed M. Sannan

6

您可以使用 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>


1
谢谢~这个解决方案对我的代码有效。值得使用。 - Milo Chen

1
最好将您的函数实现放在反引号表达式之外,像这样:

function helloworld() {

let string;

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

//Inside the backtick

`${helloworld()}`

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

然后在您的模板中执行 ${tplFor("const person of people","你好!${person.firstName}")}


0
如果你正在使用Angular/TypeScript,你可以在反引号``之间完成它。
  <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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接