我完全理解 Javascript 是区分大小写的,但是当涉及到 if 语句时,Sam 不等于 sam。我创建了一个调用此函数的提示框,我希望它在您在提示框中键入名称时将 sam 转换为 Sam 或将两者都设为 True。
function search(name) {
var ourContacts = contacts.length;
for (var i = 0; i < ourContacts; i++) {
if (contacts[i].name === name) {
printdog(contacts[i]);
}
}
}
如果您需要它以获得更好的理解,这是我的整个脚本。
function dog(name, breed, age, color, weight, owner, owneraddress) {
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
this.weight = weight;
this.owner = owner;
this.owneraddress = owneraddress;
}
//My Dogs
var sam = {
name: "Sam",
breed: "Chihuahua",
age: 7,
color: "White",
weight: "7 lb",
owner: "Bourton",
owneraddress: "44 Berkley Drive"
};
var max = {
name: "Max",
breed: "Chihuahua",
age: 4,
color: "Brown",
weight: "5 lb",
owner: "Smith",
owneraddress: "134 Door Ave"
};
//My array of dogs
var contacts = [sam, max];
function printdog(dog) {
console.log(dog.name + " " + dog.owner);
}
function list() {
var ourContacts = contacts.length;
for (var i = 0; i < ourContacts; i++) {
printdog(contacts[i]);
}
}
list();
function search(name) {
var ourContacts = contacts.length;
for (var i = 0; i < ourContacts; i++) {
name = name.toLowerCase;
if (contacts[i].name === name) {
printdog(contacts[i]);
}
}
}
<button onclick="search(prompt('Search Dogs Name'))">Search for Dog</button>