我想创建一个非常简单的脚本来检查用户对预先存在的数组的输入。但是,它似乎不起作用,我不知道为什么。请记住,我是新手并尝试学习。
<script>
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
if (usernumber == 'numbers') //If the user number matches one of preset numbers
{
alert('Match');
} else {
alert('No match found.');
}
</script>
答案 0 :(得分:4)
您可以在此处使用Array.indexOf原型函数:
if(numbers.indexOf(usernumber) >= 0){
alert('Match');
}
参考:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
答案 1 :(得分:1)
这对你来说很好用
<script>
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
for(i=0;i<=numbers.length;i++)
{if (usernumber == numbers[i])
{
alert('Match');
break;
} }
if(i==numbers.length) {
alert('No match found.');
}
</script>
答案 2 :(得分:1)
您可以查看以下代码
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
if (numbers.indexOf(usernumber) >=0 ) //If the user number matches one of preset numbers
{
alert('Match');
} else {
alert('No match found.');
}
答案 3 :(得分:1)
array.indexof(item)如果数组上不存在该项则返回-1,否则返回项目的索引
<script>
var usernumber = prompt('What is your number?');
var numbers = ['1', '2', '3'];
if (numbers.indexOf(usernumber) >=0 ) // check if the item exists on the array
{
alert('Match');
} else {
alert('No match found.');
}
</script>
答案 4 :(得分:0)
<script>
var usernumber = prompt('What is your number?');
var numbers = new Array();
numbers['1'] = true;
numbers['2'] = true;
numbers['3'] = true;
if (numbers[usernumber]) //If the user number matches one of preset numbers
{
alert('Match');
} else {
alert('No match found.');
}
</script>