在JavaScript中检查与数组的变量匹配

时间:2015-11-07 14:22:20

标签: javascript arrays loops if-statement for-loop

我正在自学JavaScript,我想编写一个简单的程序来检查用户输入是否在预先存在的数组中。

示例代码是:

 var options = ['rock','paper','scissors'];
 var choice = 'scissors';



var i;

    for (i=0;i<options.length;i++){
        if (choice === options[i]){
            console.log('match');
        }

    }

我尝试添加一个else,它会提示用户输入一个新输入,但是每当for循环遍历与输入不匹配的数组对象时它就会运行。

我的最终目标是让这个小程序在检测到他们的输入与任何数组对象都不匹配时,只提示用户输入一次新的输入。

2 个答案:

答案 0 :(得分:2)

您可以使用if语句,而不是使用for循环。

var options = ['rock', 'paper', 'scissors'];
var choice = 'scissors';

if(options.indexOf(choice) !== -1) {
  console.log('match');
}

Array.indexOf()方法在数组中搜索一个值,如果数组中不存在则返回-1。

所以你可以反过来看看是否有匹配。

if(options.indexOf(choice) === -1) {
  console.log('no match');
}

答案 1 :(得分:1)

您可以检查数组是否包含没有循环的项目使用 indexOf 方法在数组中搜索指定的项目,并返回其位置,如果项目为,则返回-1没找到,例如:

var options = ['rock','paper','scissors'];
var choice = 'scissors';

//If the input does not match any of the array objects prompt the user for a new input  
if (options.indexOf(choice) == -1)
{
     prompt("Enter new input");
}

希望这有帮助。