javascript - 在数组中查找字符串

时间:2015-02-04 06:50:44

标签: javascript arrays

通常"在数组中找到字符串#34;问题:

我目前知道如何使用for循环和if语句在数组中查找字符串。但是,如果迭代整个数组后找不到匹配的字符串,我想要做的就是返回一个选项。显而易见的问题是,如果我在当前的if语句中包含else选项,那么没有匹配的每次迭代都会移动到else。

所以基本上,我想扫描整个阵列..如果我想要打印匹配" abc"如果根本没有匹配,我想打印" xyz"。我该怎么做呢?谢谢(超级新手:))。

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");
    }
}

3 个答案:

答案 0 :(得分:1)

不需要循环

&#13;
&#13;
if(guestList.indexOf(guestName) === -1)
   return "xyz"
else
  return "abc"
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您仍想打印访客姓名,您可以提供默认的访客姓名,而不是在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);

或者使用jQuery并且没有for循环:

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

请参阅jquery inArray的文档:

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

答案 2 :(得分:0)

试试这段代码:

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