简体   繁体   English

javascript-在数组中查找字符串

[英]javascript - finding strings in an array

a little twist on the usual "finding string in an array" question: 在通常的“在数组中查找字符串”问题上稍作改动:

I currently know how to find a string in an array, using a for loop and if statement. 我目前知道如何使用for循环和if语句在数组中查找字符串。 But what I want to do is return an option if no matching string can be found once iterating through the entire array. 但是我想做的是返回一个选项,如果遍历整个数组后找不到匹配的字符串。 The obvious problem is that if I include an else option in my current if-statement, each iteration that there is no match moves to the else. 明显的问题是,如果我在当前的if语句中包含else选项,则没有匹配项的每次迭代都会移至else。

So basically, I want to scan through the entire array.. IF there's a match I want to print "abc" and if there is no match at all I want to print "xyz". 所以基本上,我想扫描整个阵列。 How do I do this? 我该怎么做呢? Thanks (super novice here :)). 谢谢(超级新手在这里:))。

var guestList = [
"MANDY",
"JEMMA",
"DAVE",
"BOB",
"SARAH",
"MIKE",
"SUZY"
];

var guestName = prompt("Hello, welcome to The Club. What is your name?").toUpperCase();

for (var i=0; i<guestList.length; i++){
    if (guestName === guestList[i]){
        alert("Hi " + guestName + " You are on the list! Enjoy The Club");
    }
}

No for loops required 无需for循环

 if(guestList.indexOf(guestName) === -1) return "xyz" else return "abc" 

If you still want to print the guest name, you can give a default guest name, and than it might be changed or not during the for loop: 如果仍要打印来宾名称,则可以提供一个默认的来宾名称,然后在for循环中可以更改或不更改它:

    var guestName = prompt("Hello, welcome to The Club. What is your name?").toUpperCase();
    var member = "GUEST";
    for (var i=0; i < guestList.length; i++) {
        if (guestName === guestList[i]){
            member = guestName;
            break;
        }
    }
    alert("Hi " + member);

Or with jQuery and without a for loop: 或使用jQuery而没有for循环:

var member = "GUEST";
if ($.inArray(guestName, guestList) > -1) {
    member = guestName;
}
alert("Hi " + member);

See the documentation of jquery inArray: 请参阅jquery inArray的文档:

http://api.jquery.com/jquery.inarray/ http://api.jquery.com/jquery.inarray/

Try this code: 试试这个代码:

 var guestList = [ "MANDY", "JEMMA", "DAVE", "BOB", "SARAH", "MIKE", "SUZY" ]; var guestName = prompt("Hello, welcome to The Club. What is your name?").toUpperCase(); var greet = "xyz";//put the default text here for (var i = 0; i < guestList.length; i++) { if (guestName === guestList[i]) { greet = "Hi " + guestName + " You are on the list! Enjoy The Club"; break;//match found, stop loop } } alert(greet);//greetings here 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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