简体   繁体   中英

How to make a loop in a javascript function using EJS

I've written this script. It works fine, but when I'm adding the loop it doesn't work. Is there a mistake in the structure of the loop or another thing?

<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>

You have to return outside of your loop and you can change a little:

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
}

For your comment:
You need to parse a string number to a valid number

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM