【问题标题】:How to make a loop in a javascript function using EJS如何使用 EJS 在 javascript 函数中创建循环
【发布时间】:2017-04-04 08:51:25
【问题描述】:

我写了这个脚本。它工作正常,但是当我添加循环时它不起作用。是循环结构有误还是别的什么?

<p id="f"></p>
<script>
    var resultat = '{ "name":"multiplication matricielle", "age":30, "city":"New York"}'
    var obj = JSON.parse(resultat);
    document.getElementById("id1").value = obj.name;
    document.getElementById("id2").value = obj.age;
    document.getElementById("id3").value = obj.city;
</script>


<script>
    function compare() {
        a = "yes";
        var i;
        for (i = 0; i < '<%=inf.length%>'; i++) {

            if ('<%=inf[i].nom%>' == obj.name && '<%=inf[i].sortie%>' == obj.city) {
                return a;
            }
        }
    }
    document.getElementById('f').innerHTML = compare();
</script>

【问题讨论】:

  • 删除 " 并在不需要的脚本标签内尝试
  • 请分享控制台日志错误
  • i ' 将不起作用 i
  • @VinodLouis inf 仍然不会被定义。
  • @Kev 是的,我也看到了它的 undefined 所以根据 inf 的值写了

标签: javascript express ejs


【解决方案1】:

你必须在你的循环之外返回,你可以稍微改变一下:

function compare() {
  var a = "No"; // <---initialize with default value
  var i;
  for (i = 0; i < parseInt('<%=inf.length%>', 10); i++) { // parse as number
    if ('<%=inf[i].nom%>' == obj.name && '<%=inf[i].sortie%>' == obj.city) {
      a = "Yes"; // if check is true change the value
    }
  }
  return a; // <--- now return it here
}

对于您的评论:
您需要将字符串数字解析为有效数字

parseInt('<%=inf.length%>', 10); // You have to parse it as number.

【讨论】:

  • 函数在没有循环的情况下工作,所以问题出在循环结构的某个地方
  • @Maki 您必须将字符串解析为循环数字。
  • 或者你也可以&lt;%- inf.length %&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多