在if语句方面,如何使Javascript不区分大小写?

时间:2012-07-27 19:39:41

标签: javascript

我完全理解Javascript是区分大小写的,但是当涉及到语句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>

3 个答案:

答案 0 :(得分:4)

你可以在相等比较器

之前在两端执行.toUpperCase()之类的操作

答案 1 :(得分:1)

只需lower-uppercase所有内容(搜索和数据)。您已尝试对name执行此操作,但不在contacts[i].name上执行此操作(并且它们的名称为“Sam”和“Max”,因此它们永远不会等同于小写输入字符串。)

此外,您忘记执行该功能 - 您只是引用了它。

function search(name) {
    var ourContacts = contacts.length;
    name = name.toLowerCase();
//                         ^^
    for (var i = 0; i < ourContacts; i++) {
        if (contacts[i].name.toLowerCase() === name) {
//                          ^^^^^^^^^^^^^^
            printdog(contacts[i]);
        }
    }
}

答案 2 :(得分:1)

您可以在两个操作数上使用Javascript .toUpperCase()方法:

if (contacts[i].name.toUpperCase() === name.toUpperCase())

或者,您可以在两个操作数上使用.toLowerCase()方法:

if (contacts[i].name.toLowerCase() === name.toLowerCase())