我已经设法为js联系人数组编写函数代码:
function searchcontacts() {
var input = document.getElementById("myInput");
var btn = document.getElementById("myBtn");
var inputcase = input.value.toUpperCase();
for (i=0; i < contacts.length; i++){
if(contacts[i].name.indexOf(inputcase) != -1) {
contacts[i].showcontact();
}
else {
continue;
document.write("no result found </br>");
}
}
}
function showcontact() {
document.write("Name:"+this.name+"<br>");
document.write("address:"+this.address+"<br>");
document.write("email:"+this.email+"<br>");
document.write("phone number:"+this.phone+"<hr>");
}
function Contact(name,address,email,phone) {
this.name=name;
this.address=address;
this.email=email;
this.phone=phone;
this.showcontact=showcontact;
}
现在我试图找到一种方法来返回字符串&#34;没有找到结果&#34;什么都没发现的因为继续;完全跳过这一步。有谁知道我该怎么做?网络开发新手!提前感谢您!
答案 0 :(得分:2)
您需要跟踪您找到的结果数量,并在循环后检查,如下所示:
function searchcontacts() {
var input = document.getElementById("myInput");
var btn = document.getElementById("myBtn");
var inputcase = input.value.toUpperCase();
var results = 0;
for (i=0; i < contacts.length; i++){
if(contacts[i].name.indexOf(inputcase) != -1) {
contacts[i].showcontact();
results++;
}
}
if(results === 0){
document.write("no result found </br>");
}
}