我写过这个剧本。它工作正常,但当我添加循环它不起作用。在循环结构或其他方面是否存在错误?
<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>
答案 0 :(得分:0)
你必须回到你的循环之外,你可以改变一点:
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.